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

Issue

I usually use a similar solution to this one. Something like:

.wrapper {
   position: relative;
   width: 100%;
   height: 0;
   padding-bottom: 56.25%;
}
.wrapper iframe {
   position:absolute;
   left: 0;
   top: 0;
   height: 100%;
   width: 100%;
}

But this time I have no access to the HTML or JavaScript code so I can’t use a wrapper to prevent the height:0.

Is there a way to make an iframe responsive (and to keep the ratio) with only CSS?

Tried this (works with the iframe but not with its content):

iframe {
    width: 100%;
    background: red;
    height: 0;
    padding-bottom: 33%;    
}

fiddle

Any thoughts? No need to support old browsers so even a CSS3 solution would be great.

Solution

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)

Answered By – Danield

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published