The approach most web developers take to make images responsive cannot be employed for videos from YouTube or Vimeo, as they deliver their content using embedded iframe elements. The generic code suggested to embed a YouTube video is as follows:
<iframe width="560" height="315"
src="http://youtube.com/embed/m4cgLL8JaVI?rel=0" frameborder="0"
allowfullscreen></iframe>
There are two primary ways to make embedded videos responsive. Before introducing the methods, we’ll strip off the redundant attributes:
<iframe src="http://www.youtube.com/embed/m4cgLL8JaVI?rel=0" allowfullscreen></iframe>
The first technique to make embedded video fluid is almost pure CSS. It only requires wrapping a div with a class around the iframe
element:
<div class="responsive-container">
<iframe src="http://youtube.com/embed/m4cgLL8JaVI?rel=0" allowfullscreen>
</iframe>
</div>
Then applying CSS to the class
and the iframe
inside:
.responsive-container {
position: relative;
padding-bottom: 56.25%;
padding-top: 30px;
height: 0;
overflow: hidden;
}
.responsive-container iframe {
position: absolute;
top: 0;
left: 0;
border: 0;
width: 100%;
height: 100%;
}
The technique uses the standard approach of placing an absolutely positioned element inside a relative one, with an offset.
The second method still uses a div
container but creates fluidity with JQuery, in the form of a plugin called FitVids, developed by Chris Coiyer, Dave Rupert, and others:
$(document).ready(function(){
$("#thing-with-videos").fitVids();
});
In the case of the code above, a <div>
container with an id
of thing-with-videos will be dynamically resized.
Note that either technique can be also used to make embedded maps responsive. However, both techniques have the same drawback: maps from Google or Bing will not center or zoom in and out as their containers expand and contract. That takes a different solution, which I will cover in the very near future.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.