如何巧妙地利用css让iframe嵌入视频/地图(固定比例自适应)

宽度随屏幕 100% 变宽时,高度也按比例(比如 16:9)自动变高。那么不需要任何 JavaScript,纯 CSS 就可以完美实现。

html 复制代码
<div class="iframe-wrapper">
  <iframe src="//player.bilibili.com/player.html?aid=386733968" allowfullscreen="allowfullscreen"></iframe>
</div>
css 复制代码
.iframe-wrapper {
  width: 100%;
  aspect-ratio: 16 / 9; /* 核心:让容器始终保持 16:9 的高宽比 */
}

.iframe-wrapper iframe {
  border: 0;
  width: 100%;
  height: 100%; /* iframe 完美填满这个 16:9 的格子 */
}

举个例子

评论