必须用 .embed-responsive 作为父容器包裹 <iframe> 并添加 .embed-responsive-item 类,否则响应式失效;需按视频源宽高比选 embed-responsive-16by9 或 4by3,避免黑边或裁剪。
用 .embed-responsive 包裹 <iframe> 才有效
bootstrap 4/5 的响应式嵌入依赖于特定的容器类,不是给 <iframe> 自己加 class 就行。必须用 .embed-responsive 作为父容器,再把 <iframe> 放进里面,并加上 .embed-responsive-item。
常见错误是直接给 <iframe> 加 .w-100 或 .ratio,结果视频拉伸变形或宽高比失效。
-
.embed-responsive是一个「占位容器」,靠 padding-top 百分比撑出宽高比(比如 16:9 → padding-top: 56.25%) -
<iframe>必须设为绝对定位、全尺寸覆盖,否则不随容器缩放 - Bootstrap 5 中改用
.ratio+ 子元素,但旧项目仍大量用.embed-responsive,别混用
示例(Bootstrap 4):
<div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/xxx" allowfullscreen></iframe> </div>
embed-responsive-16by9 和 embed-responsive-4by3 怎么选
选哪个取决于视频源本身的宽高比,不是“看着顺眼就选”。YouTube 默认是 16:9,Vimeo 多数也是;老教学视频或监控流可能是 4:3。
错配会导致黑边、裁剪或挤压——比如用 embed-responsive-4by3 包 16:9 视频,上下会多出大片空白;反过来则左右被切掉。
- 16:9:绝大多数现代视频、YouTube、Bilibili 嵌入链接默认适配
- 4:3:老课件、部分安防摄像头 RTMP 流、某些内部培训视频
- Bootstrap 5 不再内置
embed-responsive-*,改用.ratio+ CSS 自定义比例,如<div class="ratio ratio-16x9">
为什么加了 class 还不响应?检查这三点
最常卡在这几个地方,和 Bootstrap 版本、CSS 加载顺序、HTML 结构都有关。
- 没引入 Bootstrap 的 CSS(只引了 JS)——
.embed-responsive是纯 CSS 类,JS 完全不参与 - 自定义 CSS 覆盖了
.embed-responsive-item的position: absolute或top/left/right/bottom: 0 -
<iframe>上写了固定width或height属性(如width="560"),会强制覆盖响应式行为
快速验证方法:打开浏览器开发者工具,看 <iframe> 是否计算出 position: absolute 且四边为 0;它的父容器是否有正确的 padding-top 值。
移动端自动静音 + 免全屏播放要额外处理
Bootstrap 只管尺寸,不管播放逻辑。iOS Safari 和 Android Chrome 对自动播放有严格限制:没用户手势触发、没静音、没 playsinline,视频会 fallback 到全屏播放。
- 必须加
allow="autoplay; encrypted-media; picture-in-picture"和allowfullscreen - iOS 需要
webkit-playsinline+playsinline属性,否则点开就跳全屏 - 加
muted和autoplay才可能自动播放(但仅限静音)
完整 iframe 示例(YouTube):
<div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/xxx?autoplay=1&muted=1&playsinline=1" allow="autoplay; encrypted-media; picture-in-picture" allowfullscreen webkit-playsinline playsinline muted autoplay> </iframe> </div>
注意:这些属性不是 Bootstrap 提供的,但没它们,响应式容器再准也没法在手机上正常播。