Embedding YouTube videos in Jekyll
Author: | Alex Vie |
Title: | Embedding YouTube videos in Jekyll |
Language: | en-US |
Categories: | Jekyll |
Created: | 19:41 on Tuesday, 10. October 2017 |
Modified: | 19:42 on Tuesday, 10. October 2017 |
Excerpt: | A include-able fragment that allows to embed youtube videos by video ID. The video will be sized properly to the available width using CSS only. No Javascript or other dependencies needed. |
Tags: | first, jekyll, css, video |
Page layout: | default_dyn |
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.
You can write a comment
Please stick to common netiquette when posting comments. Avoid any form of personal attacks, harassment, hate speech, sexism, racism or otherwise inappropriate content. Comments that violate common rules of civilized communication among humans will be deleted without further notice.