父容器必须加 d-flex 才能使用 align-items-center,该类仅对 flex 容器生效;未设 d-flex 时样式无效,常见于 .row/.col;全屏推荐 min-vh-100 而非 h-100;多子元素整体居中需容器级 d-flex + align-items-center;背景图居中须配合 bg-no-repeat 和 bg-contain/bg-cover。
父容器必须加 d-flex 才能用 align-items-center
这个类只对 flex 容器本身起作用,不是“让子元素居中”的指令,而是“让子元素在本容器内垂直居中”的声明。很多人直接给子元素加 align-items-center,结果完全没反应——因为它的生效前提被跳过了。
常见错误现象包括:页面无变化、子元素错位、DevTools 里看到 computed display 仍是 block。尤其要注意:.row 默认不是 flex 容器,.col 或 .container 也不是,必须显式加 d-flex。
- 只加
align-items-center不加d-flex→ 样式无效 - 父容器是
<div class="col-md-6">→ 必须补d-flex,不能依赖栅格自动触发 flex - Bootstrap 4 中同理,
d-flex是前提,否则my-auto也无效
min-vh-100 比 h-100 更可靠
Flex 的 align-items-center 不会拉伸父容器,它只在已有高度内对齐。如果父容器高度为 auto(比如内容撑开、没设 min-height),那“垂直居中”就失去了参照系,视觉上还是顶着顶部。
h-100 依赖所有祖先元素都设了高度,链路一断就失效;而 min-vh-100 直接取视口高度,不依赖父级,更鲁棒。
- 全屏场景优先用
min-vh-100,不是height: 100vh(避免 iOS Safari 旧版计算偏差) - 顶部有 fixed 导航栏时,改用
min-height: calc(100vh - 60px) - 用 DevTools 查 computed height,别只看 class 名——实际为 0 就白搭
多个子元素要整体居中?别用 my-auto
my-auto 在 Bootstrap 4/5 中只对单个子元素生效,原理是 margin-top: auto; margin-bottom: auto。它不会影响其他兄弟元素,多个子项时,只有加了该类的那个会被推到中间,其余仍堆在顶部或底部。
想让整个内容块(比如标题+图片+按钮)一起垂直居中,必须用容器级方案:
- Bootstrap 5+:父容器加
d-flex align-items-center justify-content-center - Bootstrap 4:同样用
d-flex+align-items-center,my-auto只作单点微调 - 若需垂直堆叠(如列式布局),额外加
flex-column,再配justify-content-center控制主轴
背景图居中别只靠 bg-center
bg-center 只控制背景位置,不解决“整张图等比缩放后居中显示”的问题。漏掉关键配套类,图片会平铺、溢出或只居中不缩放。
必须组合使用:
-
bg-no-repeat:否则bg-center无效 -
bg-contain:等比缩放至完全可见,适合 logo 类小图 -
bg-cover:等比缩放至填满容器,适合 banner 大图 - 容器必须设明确宽高,例如
style="width: 200px; height: 200px;"
纯 CSS 的 object-fit 方案更可控,但 Bootstrap 不封装它,得手写:width: 100%; height: 100%; object-fit: contain; object-position: center; —— 这个组合要求容器有 height 且 overflow: hidden,否则容易飘移。


















