要让嵌入的 YouTube 视频在网页中宽度为 100% 并保持等比例缩放高度,有几种常用的方法。以下是最佳解决方案:
方法一:使用响应式容器包裹
这是最常用且兼容性最好的方法:
<div class="video-container">
<iframe src="https://www.youtube.com/embed/CKKnPACZUTw?si=bxAKIsPNsPI6_ekj"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin"
allowfullscreen>
</iframe>
</div>
<style>
.video-container {
position: relative;
width: 100%;
padding-bottom: 56.25%; /* 16:9 的宽高比 */
height: 0;
overflow: hidden;
}
.video-container iframe {
position: absolute;
top: 0;left: 0;width: 100%;
height: 100%;
}
</style>
方法二:使用 CSS 属性选择器
如果你有多个视频需要设置,可以使用属性选择器:
<style>
iframe[src*="youtube.com"] {
width: 100%;
aspect-ratio: 16/9; /* 现代浏览器支持 aspect-ratio */
height: auto;
}
</style>
方法三:使用 flex 或 grid 布局
<div class="video-wrapper">
<iframe src="https://www.youtube.com/embed/CKKnPACZUTw?si=bxAKIsPNsPI6_ekj"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin"
allowfullscreen>
</iframe>
</div>
<style>
.video-wrapper {
display: flex;
width: 100%;
}
.video-wrapper iframe {
flex: 1;
aspect-ratio: 16/9;
}
</style>
注意事项
- 默认 YouTube 视频宽高比为 16:9,所以
padding-bottom: 56.25%
或aspect-ratio: 16/9
能保持正确比例 - 对于旧浏览器,方法一兼容性最好
- 对于现代浏览器,方法二使用
aspect-ratio
更简洁 - 如果视频比例不是 16:9,请相应调整比例值
以上任何方法都能确保视频在任何屏幕尺寸下保持宽度 100% 并等比例缩放高度。