仅使用 CSS 的响应式视频 iframe(保持纵横比)?

新手上路,请多包涵

我通常使用与 此类 似的解决方案。就像是:

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

但是这次我无法访问 HTML 或 JavaScript 代码,所以我不能使用包装器来防止 height:0

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

试过这个(适用于 iframe 但不适用于其内容):

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

小提琴

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

原文由 Toni Michel Caubet 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 313
2 个回答

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

小提琴

iframe {
    width: 100vw;
    height: 56.25vw; /* 100/56.25 = 560/315 = 1.778 */
    background:red;
}

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

原文由 Danield 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是基于 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>

它通过如何处理填充的百分比值来解释:

该百分比是根据生成的框的包含块的宽度计算的,即使对于“padding-top”和“padding-bottom”也是如此。

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

原文由 SimonSimCity 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题