如何让Bootstrap 5卡片横向排列且不触发垂直滚动?
实现Bootstrap 5卡片横向排列并触发水平滚动
要实现你需要的横向滚动卡片布局,直接对现有结构做以下调整即可:
核心修改逻辑
借助Bootstrap的Flex布局类,配合样式限制容器高度、开启水平滚动,同时强制卡片不换行。
具体实现步骤
- 调整卡片容器类
给包裹卡片的容器添加d-flex、flex-nowrap、overflow-x-auto类,让卡片横向排列且不自动换行,超出容器宽度时触发水平滚动。 - 锁定Section滚动行为
给.section添加overflow-y-hidden类,禁止垂直方向滚动,同时保留height: 100vh确保占满浏览器窗口。 - 优化卡片间距(可选)
给每张卡片添加me-3类,让卡片之间保持合适的横向间距。
修改后的完整代码示例
HTML部分
<div class="section vh-100 overflow-y-hidden"> <div class="container d-flex flex-nowrap overflow-x-auto h-100 align-items-center"> <div class="card me-3" style="width: 18rem;"> <img src="https://via.placeholder.com/150" class="card-img-top" alt="卡片图片"> <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-primary">Go somewhere</a> </div> </div> <div class="card me-3" style="width: 18rem;"> <img src="https://via.placeholder.com/150" class="card-img-top" alt="卡片图片"> <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-primary">Go somewhere</a> </div> </div> <div class="card me-3" style="width: 18rem;"> <img src="https://via.placeholder.com/150" class="card-img-top" alt="卡片图片"> <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-primary">Go somewhere</a> </div> </div> <div class="card me-3" style="width: 18rem;"> <img src="https://via.placeholder.com/150" class="card-img-top" alt="卡片图片"> <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-primary">Go somewhere</a> </div> </div> </div> </div>
可选自定义CSS(优化滚动条)
.section { height: 100vh; } /* 自定义水平滚动条样式 */ .container::-webkit-scrollbar { height: 8px; } .container::-webkit-scrollbar-thumb { background-color: #ccc; border-radius: 4px; }
效果说明
- 卡片在水平方向连续排列,超出浏览器宽度时触发水平滚动条
- 整个section保持满屏高度,无垂直滚动
- 卡片默认垂直居中(通过
align-items-center实现,不需要可直接移除该类)
内容的提问来源于stack exchange,提问作者Sudo Sur
相关产品推荐
相关产品推荐

