加了align-items-center和justify-content-center仍不居中,根本原因是父容器缺失d-flex类或未设置明确高度(如min-vh-100),导致flex上下文和垂直参照空间均不存在。

align-items-center 和 justify-content-center 必须一起用,且只对直接子元素生效——父容器没设 d-flex 或没高度,这两个类就等于没写。
为什么加了居中类还是不居中?
根本原因就两个:d-flex 缺失、高度上下文缺失。Bootstrap 的 .row、.container 默认不是 flex 容器,align-items-center 在非 flex 环境下完全无效;而 min-height 不够时,垂直方向“可居中的空间”为 0,自然贴顶。
- 用 DevTools 检查父元素的 computed
height,别只看 class 列表 -
min-vh-100比h-100更可靠——后者依赖父级已设高,前者直接锚定视口 - 嵌套一层没加
d-flex的<div>,就会中断对齐链路 <h3>最简可靠写法:单层容器直接居中</h3> <p>适用于模态框内容、全屏 landing 页、空状态提示等场景。结构必须扁平,避免多余包裹:</p> <pre class="brush:php;toolbar:false;"><section class="d-flex justify-content-center align-items-center min-vh-100"><div class="text-center"> <h1>Hello</h1> <p>Centered both ways</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill4914" title="VPS Bootstrap"><img src="https://img.php.cn/upload/skill/000/000/081/179025304626966.jpg" alt="VPS Bootstrap" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill4914" title="VPS Bootstrap" class="overflowclass">VPS Bootstrap</a> <p class="overflowclass">从零启动全新 VPS,完成 OpenClaw 完整部署,包括备份/恢复及恢复后验证。用于 OpenClaw 部署。</p> </div> <a rel="nofollow" href="/xiazai/skill4914" title="VPS Bootstrap" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div> </div> </section></pre> <ul> <li> <code>d-flex是前提,触发 flex 布局 -
justify-content-center控制主轴(默认水平)居中 -
align-items-center控制交叉轴(默认垂直)居中 - 内部
<div> 加 <code>text-center是为了文字自身居中,和容器居中无关栅格内居中:保留 .container/.row 结构时怎么做
如果必须用 Bootstrap 栅格(比如需要响应式列宽),就不能把
d-flex直接加在.row上——它会破坏col-*的宽度计算逻辑。正确做法是让.row居中其内容,再靠内部 flex 控制垂直:<section class="min-vh-100 d-flex align-items-center"><div class="container"> <div class="row justify-content-center"> <div class="col-lg-6"> <div class="d-flex flex-column align-items-center"> <h2>Title</h2> <p>Text centered inside column</p> </div> </div> </div> </div> </section>- 外层
section用d-flex align-items-center实现垂直居中 -
.row用justify-content-center实现水平居中(仅对子.col生效) - 若需列内文字/元素也垂直居中,得在
.col内再套一层d-flex
真正容易被忽略的是:所有居中都只作用于“直接子元素”。哪怕多包一层没加
d-flex的<div>,<code>align-items-center就立刻失效——这不是 Bug,是 Flexbox 的设计逻辑。调试时优先检查 DOM 层级和 computed 样式,而不是反复改 class 名字。 - 外层










