Fluid width embedded YouTube videos

I recently posted two articles that included embedded YouTube videos and came across a couple of issues I thought deserved a post that may be of use to other Jekyll bloggers wishing to include YouTube videos on their own sites.

Fluid width YouTube videos

Firstly, the default generated HTML embed code defines a specific width/height (in px) for the iframe, this means the video will not automatically resize to fit the whole width of the container with a fluid or responsive width.

After a quick Google search, I found a very simple solution, just two rules of CSS thanks to the article ‘Fluid Width Video’ (based on code from Thierry Koblentz) on CSS-Tricks.com:

.video-wrapper {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
  padding-top: 25px;
  height: 0;
}

.video-wrapper iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

The HTML embed code then looks something like:

<div class="video-wrapper">
  <iframe src="https://www.youtube.com/embed/Og9j5Wk0Di4" frameborder="0" allowfullscreen></iframe>
</div>

With that simple solution, I can now have nicely-fitting embedded YouTube videos in my blog posts - yay!

Nicer YouTube embeds with Liquid/Jekyll

Now that’s sorted, I was wondering if I could make embedding YouTube videos even easier by creating just one Liquid template containing the video embed HTML and passing the 11 character video ID as a parameter wherever I want a YouTube video to appear.

I created the file yt-video.html in my site’s Jekyll ‘_includes’ directory containing the previously mentioned code, but with a slight modification:


<div class="video-wrapper">
  <iframe src="https://www.youtube.com/embed/{{ include.video_id }}" frameborder="0" allowfullscreen></iframe>
</div>

Now, whenever I want to include an embedded video, I simply use the following in my post/page markdown or HTML:

{% include yt-video.html video_id="[Video ID]" %}

No need to copy/paste any more HTML, just include the video’s ID, nice!