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

15,025

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%;
}
Share:
15,025
hypermails
Author by

hypermails

Updated on June 04, 2022

Comments

  • hypermails
    hypermails almost 2 years

    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 ?

  • hypermails
    hypermails over 8 years
    doesn't work well if I reduce the width to a small number - like 20% codepen.io/anon/pen/EVyYyq
  • GlabbichRulz
    GlabbichRulz almost 6 years
    why did you include padding-top: 30px;?
  • GlabbichRulz
    GlabbichRulz almost 6 years
    Without removing it, i got a black bar at the top and bottom of a 16:9 player (i guess its 30px high). Removing the padding-top: 30px; did remove the border. As i don't see it mentioned in the source either, i will suggest an edit
  • tdy
    tdy over 2 years
    Consider including an explanation of how and why this solves the problem. This will help future readers to better understand your solution. - From Review