要在网页中嵌入 YouTube 视频,并且做到宽度 100%、高度等比例自适应,目前最推荐的两种写法如下:
方法一、最推荐(2024–2026 仍然最佳实践)
<div class="video-container">
<iframe
src="https://www.youtube.com/embed/bZ9NxmIPQqQ"
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-top: 56.25%; /* 16:9 = 9/16 = 0.5625 → 56.25% */
overflow: hidden;
}
.video-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
为什么用 padding-top: 56.25%?
因为 YouTube 大多数视频是 16:9 比例,9 ÷ 16 = 0.5625,所以 padding-top 设成 56.25% 就能保持比例。
方法二、更现代写法(使用 aspect-ratio,浏览器支持已非常好)
<div class="video-wrapper">
<iframe
src="https://www.youtube.com/embed/bZ9NxmIPQqQ"
title="YouTube video player"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen>
</iframe>
</div>
<style>
.video-wrapper {
width: 100%;
aspect-ratio: 16 / 9;
background: black; /* 可选:防止加载前闪烁 */
}
.video-wrapper iframe {
width: 100%;
height: 100%;
border: 0;
}
</style>
常见变体比例速查表
| 视频比例 | padding-top 值 | aspect-ratio 值 | 适用场景 |
|———-|—————-|———————|———————|
| 16:9 | 56.25% | 16 / 9 | 大多数 YouTube 视频(推荐) |
| 4:3 | 75% | 4 / 3 | 老视频、一些纪录片 |
| 21:9 | ≈42.86% | 21 / 9 或 2.33 / 1 | 超宽屏电影预告片 |
| 9:16 | 177.78% | 9 / 16 | 竖屏短视频(Reels/TikTok风格) |
小提示
- 记得把 `watch?v=` 改成 `embed/`
错误:`https://www.youtube.com/watch?v=bZ9NxmIPQqQ`
正确:`https://www.youtube.com/embed/bZ9NxmIPQqQ` - 如果想要自动播放 + 静音(移动端比较容易成功):
src=”https://www.youtube.com/embed/bZ9NxmIPQqQ?autoplay=1&mute=1″ - 如果你使用的是 Tailwind CSS,可以这样写:
<div class="relative w-full pt-[56.25%]">
<iframe class="absolute inset-0 w-full h-full" …></iframe>
</div>
<!– 或使用 aspect-ratio –>
<div class="w-full aspect-video">
<iframe class="w-full h-full" …></iframe>
</div>
选方法一或方法二都可以,目前(2026年)两种在主流浏览器都非常稳定。






