Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

html - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...