只有CSS的响应式视频iframe(保持宽高比)?

Ton*_*bet 40 html css iframe responsive-design

我通常使用一个类似的解决方案,这一项.就像是:

.wrapper {
   position: relative;
   width: 100%;
   height: 0;
   padding-bottom: 33%;
}
.wrapper iframe {
   position:absolute;
   left: 0;
   top: 0;
   height: 100%;
   width: 100%;
}
Run Code Online (Sandbox Code Playgroud)

但这次我无法访问HTML或JavaScript代码,因此我无法使用包装器来阻止height:0.

有没有办法让iframe响应(并保持比例)只有CSS?

试过这个(与iframe一起使用但不与其内容一起使用):

iframe {
    width: 100%;
    background: red;
    height: 0;
    padding-bottom: 33%;    
}
Run Code Online (Sandbox Code Playgroud)

小提琴

有什么想法吗?无需支持旧浏览器,因此即使是CSS3解决方案也会很棒.

Sim*_*ity 50

这是一个解决方案的小提琴,它基于CSS2秘密: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>
Run Code Online (Sandbox Code Playgroud)

它的解释是如何处理填充的百分比值:

百分比是根据生成的框的包含块的宽度计算的,即使对于"填充顶部"和"填充底部"也是如此.

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

  • "但这次我无法访问html代码或javascript,所以我不能使用包装器来防止高度:0" (2认同)
  • 比所选答案更灵活,因为它可以适应任何容器大小,而不仅仅是视口! (2认同)

Dan*_*eld 42

使用新的CSS视口单位 vwvh(视口宽度/视口高度)

小提琴

iframe {
    width: 100vw; 
    height: 56.25vw; /* 100/56.25 = 560/315 = 1.778 */
    background:red;  
}
Run Code Online (Sandbox Code Playgroud)

浏览器支持也不错:IE9 +(caniuse)

  • 仅当您希望iframe与视口大小匹配时才有效.但是,如果您需要适应可用宽度的内容(即iframe元素的父元素的内容宽度),则需要通过SimonSimCity查看答案. (13认同)

jon*_*tro 21

使用 css长宽比就很容易了。

iframe {
  height: auto;
  width: 100%;
  aspect-ratio: 16 / 9;
}
Run Code Online (Sandbox Code Playgroud)


Bob*_*bík 9

Calc函数使其更具可读性:

.iframe-video {
    width: 755px;
    height: 424px;
    max-width: 100%;
    max-height: calc((100vw - 40px) / (16/9));
}
Run Code Online (Sandbox Code Playgroud)
  • width并且height是桌面的大小,也回退到古老的浏览器
  • 40px 是边距(iframe 边框和两侧视口边框之间的 20 像素)
  • 16/9 是视频的比例(如果您有边对边播放器)