H3XED
Web Development   Browse Topics

How To Make a Responsive 100% Width YouTube iFrame Embed

Posted Aug 13, 2014 by Nick Vogt
The key to creating a responsive YouTube embed is with padding and a container element, which allows you to give it a fixed aspect ratio. You can also use this technique with most other iframe-based embeds, such as slideshows.

Here is what a typical YouTube embed code looks like, with fixed width and height:

<iframe width="560" height="315" src="//www.youtube.com/embed/yCOY82UdFrw" 
frameborder="0" allowfullscreen></iframe>

It would be nice if we could just give it a 100% width, but it won't work as the height remains fixed. What you need to do is wrap it in a container like so (note the class names and removal of the width and height):

<div class="container">
<iframe src="//www.youtube.com/embed/yCOY82UdFrw" 
frameborder="0" allowfullscreen class="video"></iframe>
</div>

And use the following CSS:

.container {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 56.25%;
}
.video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

How this works: The container element is given a zero height and a percentage bottom padding. The percentage bottom padding is a percentage of the container width, so that gives it a fixed aspect ratio. But in order to get the iframe to show up inside the zero-height container, you need to make the container relative and the iframe absolute, positioned inside the div.

Here is the result:




Alternative Using Media Queries


You can also use media query breakpoints to resize an iframe to specific sizes. It can be a more cumbersome solution, but does avoid the need for a container element.
Share This Post
Facebook Twitter
Web Dev Resources
Best Selling HTML & CSS Book
Best Selling HTML & CSS Book
See More Details
Best Selling Web Design Book
Best Selling Web Design Book
See More Details

Comments


Share This Post
Facebook Twitter
Web Dev Resources
Best Selling HTML & CSS Book
Best Selling HTML & CSS Book
See More Details
Best Selling Web Design Book
Best Selling Web Design Book
See More Details
H3XED © Nick Vogt   RSS   Privacy Policy   Facebook   Twitter   Google+