Bootstrap 5卡片内iframe仅宽度可缩放,如何实现高度响应?
解决Bootstrap 5卡片中iframe高度响应式的问题
你遇到的问题核心是用了Bootstrap 4的旧类,Bootstrap 5已经把响应式嵌入的类换掉了,按下面的步骤改就能解决:
- 把原来的
embed-responsive embed-responsive-4by3容器类换成Bootstrap 5的ratio ratio-4x3,这是官方现在推荐的响应式比例容器类 - 修正iframe里的样式语法错误:原代码里的
style: width="100%" height="100%"是错的,把冒号改成等号,或者直接给iframe加w-100 h-100的Bootstrap工具类,更符合框架规范 - 另外Bootstrap 5已经不需要jQuery依赖了,你代码里引入的jQuery可以删掉,减少冗余
修改后的完整代码:
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet"/> <div class="container"> <div class="row g-0"> <div class="col-12"> <div class="card mt-4 w-100"> <div class="ratio ratio-4x3"> <iframe class="w-100 h-100" src="https://www.youtube.com/embed/vlDzYIIOYmM" allowfullscreen></iframe> </div> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-dark">Go somewhere</a> </div> </div> </div> </div> </div>
补充说明:ratio类是通过给容器设置百分比的padding-top来实现响应式高度的,内部的iframe设置宽高100%后,就会自动跟着容器的宽度等比例缩放高度。如果需要其他比例,比如常见的16:9,就用ratio-16x9;要是自定义比例,还可以用CSS变量,比如给容器加style="--bs-aspect-ratio: 21/9;"就能实现21:9的比例。
内容的提问来源于stack exchange,提问作者Buddy Buie
相关产品推荐
相关产品推荐

