持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第 3 天,点击查看活动详情
iframe 响应式问题
与 img 和原生 HTML5 video 元素不同,iframe 默认情况下不会响应式缩放。
/**
* 这行不通
*/
iframe {
max-width: 100%;
height: auto;
}
解决此问题的旧方法
从历史上看,要使 iframe 具有响应性,需要将 iframe 包装在 div 容器中。
<div class="responsive-iframe">
<iframe
src="/path/to/file"
width="640"
height="360"
frameborder="0"
allow="autoplay; fullscreen; picture-in-picture"
allowfullscreen
>
</iframe>
</div>
然后,您可以使用 CSS
- 将
iframe放在div的左上角。 - 使其达到
div元素height和width的100%。 - 为
div的padding-top添加等于iframe的纵横比(对于高清视频,为56.25%或9/16*100)。
.responsive-iframe {
max-width: 100%;
padding-top: 56.25%;
position: relative;
width: 100%;
}
.responsive-iframe iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
如您所见,这是令人讨厌和复杂的。
有一个 FluidVids.js 库,帮助我们减少这种操作。
但是现在,有一个更好的方法!
CSS aspect-ratio 属性
CSS aspect-ratio 属性告诉浏览器,在向上或向下缩放某个元素时,要在该元素上保留特定的纵横比。
我们可以使用几行 CSS 直接针对 iframe 元素,以在响应性布局中保留它们的尺寸,而不需要额外的元素进行包装。
将 iframe 的 height 和 width 设置为 100%。然后将 aspect-ratio 属性的值指定为 width / height。对于高清视频,我们将使用 16 / 9。
iframe {
aspect-ratio: 16 / 9;
height: 100%;
width: 100%;
}
现在,我们可以按原样包含元素 iframe,它们会随着布局放大或缩小。
<iframe
src="/path/to/file"
width="640"
height="360"
frameborder="0"
allow="autoplay; fullscreen; picture-in-picture"
allowfullscreen
>
</iframe>
以上是一个使用 aspect-ratio 解决 iframe 响应式缩放的示例。如需了解更多,这里还整理了关于 aspect-ratio 属性的相关文章供大家参考:
- Create Responsive Image Effects With CSS Gradients And aspect-ratio
- Designing An Aspect Ratio Unit For CSS
本文首发 blog,如果喜欢或者有所启发,欢迎 Star,对作者也是一种鼓励。