You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap 4实现容器垂直对齐时出现垂直溢出滚动问题

Bootstrap4 容器垂直居中溢出问题修复方案

核心问题点

出现垂直对齐失效、视口溢出滚动,是三个结构和样式冲突导致的:

  • 外层flex容器和.row元素之间多了一层无样式的.wrapper空节点,flex布局的对齐规则仅作用于直接子元素,写在.row上的my-auto无法被外层flex容器识别,自然无法实现垂直居中。
  • 外层容器同时添加了container和container-fluid两个互斥类,前者是固定响应式宽度、后者是100%视口宽度,样式冲突会导致布局计算异常。
  • 浏览器默认给body标签添加了8px外边距,容器设置vh-100后加上这8px边距,总高度超出视口,直接触发页面滚动。

修复步骤

  1. 清理外层容器冗余类:移除重复的container类,保留container-fluid,添加vh-100(小屏适配可替换为min-vh-100)设置满视口高度,保留d-flex flex-column启用纵向flex布局。
  2. 删除多余的.wrapper嵌套层,让两个.row节点直接作为外层flex容器的子元素,给承载卡片的行添加my-auto,即可自动实现垂直居中。
  3. 清除body默认外边距,避免高度溢出。

可直接运行的修复后代码

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<style>
/* 自定义样式放在这里即可,不会影响垂直对齐逻辑 */
body {
  margin: 0; /* 清除浏览器默认外边距,消除多余滚动条 */
}
.bg-black {
  background: #000;
}
.text-on-dark {
  color: #fff;
}
.btn-gold {
  background: #ffd700;
  color: #000;
}
.card {
  height: 400px; /* 原需求里的卡片固定高度 */
}
</style>

<div class="container-fluid d-flex flex-column vh-100">
    <div class="row">
        <div class="offset-2 col-sm-4">
            <span>Title</span>
        </div>
    </div>

    <div class="row my-auto w-100">
        <div class="offset-2 col-sm-4">
            <div class="card bg-black">
                <div class="card-body text-center d-flex flex-column">
                    <img class="mx-auto" src="https://via.placeholder.com/100"/>
                    <h2 class="card-title text-center text-on-dark font-weight-bold">Mentor</h2>
                    <p class="card-text text-left text-on-dark px-5">Yada yada yada</p>
                    <button type="button" class="btn btn-gold btn-lg rounded-pill align-self-center mt-auto mb-3" style="width: 230px">GRADE</button>
                </div>
            </div>
        </div>

        <div class="col-sm-4">
            <div class="card bg-primary">
                <div class="card-body text-center d-flex flex-column">
                    <img class="mx-auto" src="https://via.placeholder.com/100"/>
                    <h2 class="card-title text-center text-white font-weight-bold">Student</h2>
                    <p class="card-text text-left text-white px-5">Blah blah blah</p>
                    <button type="button" class="btn btn-white btn-lg rounded-pill align-self-center mt-auto mb-3" style="width: 230px">STUDY</button>
                </div>
            </div>
        </div>
    </div>
</div>

注意事项

  • 如果需要适配移动端小屏幕,把外层容器的vh-100替换为min-vh-100即可,容器高度会随内容自动撑开,不会出现内容裁切问题。
  • 使用flex布局做对齐时,不要在flex容器和目标对齐元素之间嵌套无意义的空标签,否则会隔断flex的对齐规则,导致属性失效。
  • 原有卡片内部的flex布局写法是正确的,不需要调整。

内容的提问来源于stack exchange,提问作者cjames

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 07:03:27