iFrame Height Auto (CSS)

I had this same issue but found the following that works great:

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="https://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="https://www.youtube.com/embed/yCOY82UdFrw" 
 frameborder="0" allowfullscreen class="video"></iframe>

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%;

Here is the page I found the solution on:


Depending on your aspect ratio, you will probably need to adjust the padding-bottom: 56.25%; to get the height right.

Leave a Comment