Bootstrap5新建section显示在上一section下方的问题排查
问题原因
布局异常核心由两个问题导致:
- Flex方向类存在冗余写法,响应式断点逻辑混乱:你同时写了
flex-column(全局纵向)、flex-md-column(md断点纵向)、flex-lg-row(lg断点横向)三个方向类,冗余类很容易被自定义样式、版本差异影响出现规则覆盖,且md断点(768px~991px)本身就被设置为纵向排列,窗口宽度在这个区间时卡片自然会上下堆叠。 - 卡片缺少响应式宽度与间距适配:Bootstrap的
card组件默认宽度随内容撑开,纵向排列时没有设置底部间距,横向排列时也没有宽度约束,很容易因为内容过宽(比如卡片内大尺寸图片)导致布局溢出、排列错位。
修复方案
- 清理冗余的Flex方向类,只保留必要的响应式规则:默认小屏纵向排列,lg(≥992px)及以上断点横向排列
- 给卡片添加响应式间距与宽度约束,小屏下占满宽度、加底部外边距避免卡片贴连,大屏下自动适配宽度
- 若需要大屏下卡片等高排列,移除
align-items:center即可(该属性会让交叉轴方向的子元素收缩为内容高度,无法自动拉伸等高)
修正后代码
<div class="container-fluid room py-4"> <h2 class="room-section-title text-center mb-5"> Our Rooms</h2> <!-- 清理冗余flex类,保留必要的方向规则 --> <div class="container d-flex justify-content-evenly align-items-center flex-column flex-lg-row"> <!-- 卡片添加响应式宽度、间距类 --> <div class="card mx-3 mb-4 mb-lg-0 w-100" style="max-width: 360px;"> <img src="/assets/images/room/Deluxe.jpg" class="card-img-top" alt="Superior Room"> <div class="card-body"> <h5 class="card-title">Superior Room</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> <div class="btn"> <a class="text-primary text-decoration-none" href="#">Room detail</a> </div> </div> </div> <div class="card mx-3 mb-4 mb-lg-0 w-100" style="max-width: 360px;"> <img src="/assets/images/room/Deluxe.jpg" class="card-img-top" alt="Deluxe Room"> <div class="card-body"> <h5 class="card-title">Deluxe Room</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> <div class="btn"> <a class="text-primary text-decoration-none" href="#">Room detail</a> </div> </div> </div> <div class="card mx-3 w-100" style="max-width: 360px;"> <img src="/assets/images/room/Deluxe.jpg" class="card-img-top" alt="Suite Room"> <div class="card-body"> <h5 class="card-title">Suite Room</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> <div class="btn"> <a class="text-primary text-decoration-none" href="#">Room detail</a> </div> </div> </div> </div> </div>
补充说明
如果需要在更小的桌面尺寸(比如md断点,≥768px)就实现横向排列,只需要把flex-lg-row改成flex-md-row即可,对应卡片的mb-lg-0也同步改成mb-md-0。如果不需要限制卡片最大宽度,删掉卡片上的style="max-width: 360px;"就行。
内容的提问来源于stack exchange,提问作者wira
相关产品推荐
相关产品推荐

