Responsive video iframes (keeping aspect ratio) with only CSS?

Here is a Fiddle for a solution, that is based on a CSS2 secret: https://jsfiddle.net/59f9uc5e/2/

<div class="aspect-ratio">
  <iframe src="" width="550" height="275" frameborder="0"></iframe>
</div>

<style>
/* This element defines the size the iframe will take.
   In this example we want to have a ratio of 25:14 */
.aspect-ratio {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%; /* The height of the item will now be 56.25% of the width. */
}

/* Adjust the iframe so it's rendered in the outer-width and outer-height of it's parent */
.aspect-ratio iframe {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}
</style>

It is explained by how percentage-values for padding are handled:

The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'.

https://www.w3.org/TR/CSS2/box.html#padding-properties


Use the new CSS viewport units vw and vh (viewport width / viewport height)

FIDDLE

iframe {
    width: 100vw; 
    height: 56.25vw; /* 100/56.25 = 560/315 = 1.778 */
    background:red;  
}

Browser support is also good: IE9+ (caniuse)


Calc function makes it much more readable:

.iframe-video {
    width: 755px;
    height: 424px;
    max-width: 100%;
    max-height: calc((100vw - 40px) / (16/9));
}
  • width and height is size for desktop and also fallback to ancient browsers
  • 40px is margin (20 px between iframe border and viewport border on both sides)
  • 16/9 is ratio of video (if you have edge-to-edge player)