silvercircle/github/io
A Jekyll test site with no particular purpose.

Embedding YouTube videos in Jekyll

Last modified:
309 Words
By Alex Vie in Jekyll | Tue, 10. 10 2017, 19:41
Reading time: approx. 1 minute(s).

Throughout this site, I use the following HTML fragment to include videos from YouTube, passing only the video ID as a parameter. The IFRAME is wrapped into two DIV elements, the outer one being responsible for setting the overall width of the element and the inner one containing the CSS “magic” that let it maintain correct aspect ratio.

1
2
3
4
5
6
7
8
9
{% if include.width != '' %}
  <div style="width: {{include.width}}; margin:0 auto;">
{% else %}
  <div>
{% endif %}
  <div class="ytcontainer">
    <iframe class="yt" allowfullscreen src="https://www.youtube.com/embed/{{include.id}}"></iframe>
  </div>
</div>
Use it with:
{% include youtube.html id="8lsvjdkQ" %}

Specify an optional width for the outer container:

{% include youtube.html id="8lsvjdkQ" width="80%" %}


The required CSS

The following CSS is required for smooth and responsive embedding of a video element. The resulting video will use all the available width of the parent container and resize itself accordingly to use a 16:9 aspect ratio (which is the default for the YouTube video player). The available width is, by default, set to 100% of the parent element, but can be specified as percentile or absolute width by passing it in the width parameter.

The CSS and how it works is explained in more detail in this post.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
div.ytcontainer {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 56.25%;
}
iframe.yt {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: 0;
}

Example

As you can test, it is fully responsive and will adjust its width while maintaining correct aspect ratio.

jekyll css video