最稳方案是父容器设 display: flex + justify-content: center + align-items: center,并确保父容器有明确高度(如 min-height: 100vh);text-center 和 align-middle 不适用于块级元素垂直居中。
用 display: flex 最直接,但得注意父容器高度
bootstrap 本身不提供“文字居中”专用类,靠的是 css 布局能力。现代最稳的方案就是给容器加 display: flex + justify-content: center + align-items: center。
关键点在于:父 <div> 必须有明确高度(比如 height: 200px 或 min-height: 100vh),否则 align-items: center 没效果——因为内容高度撑开容器,垂直方向没“可居中空间”。
- 别只加
text-center(它只管水平,不管垂直) - 别依赖
align-middle(那是针对 inline 元素或 table-cell 的,对普通 div 无效) - 如果父容器是 Bootstrap 的
col或card-body,记得额外设高,它们默认高度由内容决定
示例:
<div class="d-flex justify-content-center align-items-center" style="height: 300px;"> <p>我要居中</p> </div>
Bootstrap 5 自带的 text-center 和 align-middle 别混用
text-center 是作用于文本对齐的,本质是 text-align: center;align-middle 是为 <img> 或 <span> 这类 inline 元素设计的,依赖 vertical-align: middle,对块级 <p> 或 <div> 完全不起作用。
- 写
<div class="text-center align-middle"><p>文字</p></div>→ 垂直无效 - 在
<table>里用align-middle可以,但那是 table-cell 场景,不是通用居中方案 - 如果非要用
vertical-align,得配合display: table-cell和height,但语义错、兼容性差,不推荐
响应式场景下,用 min-height: 100vh 比固定像素更可靠
做登录页、引导页这类需要“视口内居中”的场景,硬写 height: 500px 在小屏上会溢出,在大屏上又留白太多。用 min-height: 100vh 更合理,再配合 flex 居中,能自适应各种设备。
-
vh单位在 iOS Safari 早期版本有滚动条高度计算 bug,但 iOS 15+ 和所有现代安卓浏览器都正常 - 如果页面顶部有 fixed 导航栏,用
min-height: calc(100vh - 60px)才准,不然文字会被遮住 - 避免同时设
height: 100vh和min-height,后者会被前者覆盖
示例:
<div class="d-flex justify-content-center align-items-center" style="min-height: 100vh;"> <h2>欢迎回来</h2> </div>
IE11 兼容?别用 flex,改用绝对定位 + transform
如果项目还必须支持 IE11,display: flex 的 align-items 在某些子版本里表现异常(尤其嵌套 flex 容器时)。稳妥做法是退回到绝对定位方案:
- 父容器设
position: relative - 子元素设
position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) - 不需要知道子元素尺寸,
transform自动偏移一半 - Bootstrap 4/5 都没内置这套类,得自己加 utility 类或内联样式
示例:
<div style="position: relative; height: 300px;"> <p style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: 0;">IE11 友好</p> </div>
实际项目里最容易漏的是父容器高度控制——flex 居中不是“设了就中”,而是“有空间才中”。很多问题表面是居中失效,根子在 height 没设或设错了。


















