Responsive video iframes (keeping aspect ratio) wi

2019-01-22 02:13发布

问题:

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

.wrapper {
   position: relative;
   width: 100%;
   height: 0;
   padding-bottom: 33%;
}
.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.

回答1:

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)



回答2:

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%; /* The height of the item will now be 56% 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



回答3:

This is kind of hackish however you can use images to preserve the aspect ratio of a video. For example I went to paint and saved an image of 1280 x 720 resolution to use for a 16:9 aspect ratio (in here I will just grab a blank image off the internet somewhere).

This works because if you change the width of an image while leaving height auto, vise-versa the image will automatically scale - keeping proportions.

img {
  display: block;
  height: auto;
  width: 100%;
}
iframe {
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
}
.wrapper {
  float: left;
  position: relative;
}
<div class="wrapper">
  <img src="http://www.solidbackgrounds.com/images/1280x720/1280x720-ghost-white-solid-color-background.jpg" alt=""/>
  <iframe width="560" height="315" src="https://www.youtube.com/embed/HkMNOlYcpHg" frameborder="0" allowfullscreen></iframe>
</div>