Bootstrap 5垂直居中最快方案是父容器加d-flex align-items-center h-100(或min-vh-100),关键在父容器必须有高度且为flex容器;Grid方案用d-grid place-items-center更简洁;绝对定位仅作兜底。
用 align-items-center 配合 d-flex 最快生效
bootstrap 5 默认用 flexbox 布局,垂直居中不靠 margin 或 position,而是靠 flex 容器的对齐属性。关键不是加 class 到内容上,而是加到它的**直接父容器**上。
-
display: flex必须由父容器触发,所以父元素得加d-flex - 垂直居中用
align-items-center(适用于单行子项);如果子项是多行且需整体居中,改用justify-content-center+min-height: 100vh - 别在子元素上加
align-self-center——它只对单个子项起作用,且依赖父容器已是 flex - 如果父容器有 padding 或 border,可能遮挡视觉居中效果,建议用
h-100或min-vh-100显式撑高
<div class="d-flex align-items-center h-100"> <div>我要垂直居中</div> </div>
遇到 height: 0 或内容塌陷,先查父容器高度
Flex 垂直居中失效,90% 是因为父容器没高度。Flex 的 align-items 不会“拉伸”父容器,它只在已有高度内对齐。
- 常见错误:父容器是
<div>,没设height、min-height,也没继承父级高度 → 实际高度为 0 → 居中无意义 - 推荐方案:
min-vh-100(占视口 100% 高度),比h-100更可靠,后者依赖父级已设高 - 如果父容器是
.row,默认不是 flex 容器,必须额外加d-flex,否则align-items-center无效 - 用浏览器 DevTools 检查父容器 computed height,不是看 class,是看实际渲染高度
Grid 方案:用 place-items-center 替代 Flex
Bootstrap 5.3+ 支持 CSS Grid 工具类,适合更简单的居中场景,尤其当不需要 flex 的其他能力(如换行、排序)时。
- 父容器加
d-grid+place-items-center,一行代码搞定居中,无需关心高度继承问题 - 注意:
place-items-center同时控制水平和垂直居中,不能单独只垂直 - 兼容性稍弱于 Flex:IE 不支持,但 Bootstrap 官方已放弃 IE,可放心用
- 性能几乎无差别,但语义更清晰——你只是想“把里面的东西放中间”,不是要布局流
<div class="d-grid place-items-center min-vh-100"> <div>我也能垂直居中</div> </div>
绝对定位 + transform 是最后兜底手段
当父容器无法加 class(比如第三方组件封装死)、或需要兼容极老环境(Bootstrap 4 且不能升级),才考虑这个方案。
- 父容器必须设
position: relative(用position-relativeclass) - 子元素加
position-absolute top-50 start-50 translate-middle -
translate-middle是关键:它自动抵消自身宽高的 50%,比手动写transform: translate(-50%, -50%)更安全 - 缺点明显:脱离文档流,可能遮挡其他内容;响应式下易错位;父容器若有滚动,需额外处理
transform的层叠上下文


















