如何用 CSS 响应式嵌入 YouTube 视频
要响应式嵌入 YouTube 视频,可以让 iframe 填满容器,并给包裹它的元素设置 aspect-ratio: 16 / 9。示例将宽度限制为 960px,并让播放器在窄栏中随之缩小。
从 YouTube 复制嵌入地址
在视频页面选择分享 → 嵌入,复制显示的代码。如果没有这个选项,或视频无法嵌入,请查看YouTube 视频嵌入指南及视频的嵌入设置。
在 iframe 的 src 中使用 youtube.com/embed/视频ID 形式的地址。普通的 watch?v= 地址可留作直接观看的链接。嵌入代码中的 560×315 是默认尺寸,可以用 CSS 覆盖。
用 CSS 保持 16 比 9
外层容器占用可用宽度,上限由 max-width 决定。内层用 CSS aspect-ratio 规范 计算 16:9 的高度。iframe 相对内层定位,并填满它的宽度和高度。
把代码保存为 UTF-8 编码的 example.html,再调整浏览器窗口宽度。换成自己的视频时,修改 src 和 title。要检查播放,请通过网站或本地开发服务器提供文件,并打开 http:// 或 https:// 地址。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>响应式嵌入 YouTube 视频的示例</title>
<style>
.video-embed {
width: 100%;
max-width: 960px;
margin: 0 auto;
}
.video-embed__frame {
position: relative;
aspect-ratio: 16 / 9;
}
.video-embed__frame iframe {
position: absolute;
top: 0;
left: 0;
display: block;
width: 100%;
height: 100%;
border: 0;
}
</style>
</head>
<body>
<div class="video-embed">
<div class="video-embed__frame">
<iframe
src="https://www.youtube.com/embed/ybhXVSAdIRE"
title="Marvel Korea 的《复仇者联盟4:终局之战》最终预告"
width="560"
height="315"
loading="lazy"
referrerpolicy="strict-origin-when-cross-origin"
allow="encrypted-media; picture-in-picture"
allowfullscreen
></iframe>
</div>
</div>
</body>
</html>
父容器为 360px 时,播放器区域约为 360×202.5px。父容器超过 960px 时,上限为 960×540px。16:9 的高度等于宽度乘以 9 / 16。
检查播放器尺寸和控件
YouTube 播放器尺寸要求要求播放器区域至少为 200×200px,并建议 16:9 播放器至少为 480×270px。请在实际页面中检查控件是否完整。如果列宽太窄,无法提供 200px 高度,可以给读者提供直接观看的链接。
如果无法打开播放器,可以在 YouTube 上观看原版预告。
为 iframe 提供描述性的 title,方便屏幕阅读器识别。loading="lazy" 可以推迟加载离屏较远的播放器,allowfullscreen 允许全屏播放。
处理旧浏览器和播放错误
如果目标浏览器或 WebView 不支持 aspect-ratio,可以把示例的 .video-embed__frame 规则替换为下面的 CSS。保留外层的 max-width 和 iframe 样式。
.video-embed__frame {
position: relative;
height: 0;
padding-top: 56.25%;
}
百分比形式的竖直内边距按包含块的宽度计算。56.25% 等于 9 除以 16,绝对定位的 iframe 会填满预留区域。
尺寸正确但无法播放时,请检查视频是否允许嵌入,以及 src 是否使用 /embed/。根据YouTube 播放器错误代码,错误 153 表示缺少来源标头或等效标识。可从 HTTP 服务器打开页面,并检查网站是否移除了来源标头。




