Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 231
Toni Michel Caubet Avatar asked Aug 14 '14 07:08

Toni Michel Caubet


People also ask

How do I keep a iframe aspect ratio?

In the HTML, put the player <iframe> in a <div> container. In the CSS for the <div>, add a percentage value for padding-bottom and set the position to relative, this will maintain the aspect ratio of the container. The value of the padding determines the aspect ratio. ie 56.25% = 16:9.

How do I keep aspect ratio in CSS?

css('padding-bottom', ratio); }); And having this you just set attr data-keep-ratio to height/width and that's it.

Can iframes be made responsive?

The iframe itself ('the box') can be responsive. But everything inside the iframe is a separate page, and therefore not in the domain of your CSS nor JS.


2 Answers

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

like image 88
SimonSimCity Avatar answered Oct 14 '22 16:10

SimonSimCity


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)

like image 29
Danield Avatar answered Oct 14 '22 17:10

Danield