creating a 16:9 aspect ratio iframe based on browser size (percentage)

hypermails picture hypermails · Sep 19, 2015 · Viewed 9.3k times · Source

how can I set a iframe size (in my case - featherlight iframe playing youtube) to be a percentage of the browser windows ?

I have a browser that may be any size, and I want to set the iframe width to be 80% of browser window..

16:9 aspect ratio with fixed width mentions how to set the 16:9 height once I select a width. I don't understand how to use it.

any jsfiddle example (or codepen) will help a lot. I have tried a bunch of different ways - but the iframe does not maintain aspect ratio.

http://codepen.io/anon/pen/zvqQgq

<iframe src="https://www.youtube.com/embed/YAcLViTHDOo" width="50%" class="player" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>

How can I set the width to be 80% of browser window and allow height to be 16:9 ratio of the 80% of the width ?

Answer

andlrc picture andlrc · Sep 19, 2015

If you add a wrapper div you can get CSS to do the trick:

<div class="fluidMedia">
    <iframe src="" frameborder="0"> </iframe>
</div>
<div class="fluidMedia" style="width:80%;">
    <iframe src="" frameborder="0"> </iframe>
</div>

CSS:

.fluidMedia {
    position: relative;
    padding-bottom: 56.25%; /* proportion value to aspect ratio 16:9 (9 / 16 = 0.5625 or 56.25%) */
    height: 0;
    overflow: hidden;
}

.fluidMedia iframe {
    position: absolute;
    top: 0; 
    left: 0;
    width: 100%;
    height: 100%;
}

All credit goes to: http://www.bymichaellancaster.com/blog/fluid-iframe-and-images-without-javascript-plugins/