hypermails
hypermails

Reputation: 746

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

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 ?

Upvotes: 7

Views: 21521

Answers (2)

Andreas Louv
Andreas Louv

Reputation: 47117

In modern browsers you can use the aspect-ratio css property:

<iframe src="" frameborder="0"></iframe>

and the css:

iframe {
  aspect-ratio: 16 / 9;
  width: 100%; /* change this to a fixed width, or create a container with a width. */
  height: 100%;
}

https://caniuse.com/mdn-css_properties_aspect-ratio

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

Upvotes: 14

mayur bansal
mayur bansal

Reputation: 11

HTML:

<iframe src="" frameborder="0" class="sixteenByNineFrame"> </iframe>

CSS:

.sixteenByNineFrame{
    width: 80%;
    height: calc(80% / (16/9));
}

we want width/height = 16/9 so if we have width=80.

then, height = (width / (16/9))

Upvotes: 0

Related Questions