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

无法通过Bootstrap实现div中h2标签居中,求助排查解决

解决Bootstrap中div内h2标签居中问题

你代码里的核心问题是:Bootstrap没有内置vertical-center这个类,写了也不会生效。另外要分水平居中和垂直居中两种情况来调整:

仅水平居中

如果只需要让h2文字水平居中,直接用Bootstrap自带的text-center类就足够,注意去掉无效的vertical-center:

<div class="col-4">
    <h2 class="text-center">Text here</h2>
</div>

要是这样还不生效,检查一下父元素col-4有没有自定义的text-align样式,可能会覆盖text-center的效果。

垂直+水平双居中

如果需要让h2在div里同时垂直和水平居中,得用Bootstrap的Flex布局类来实现:

方案1:给父容器设置Flex布局

<div class="col-4 d-flex justify-content-center align-items-center" style="height: 200px;">
    <h2>Text here</h2>
</div>
  • d-flex:把父容器转为Flex布局
  • justify-content-center:实现水平方向居中
  • align-items-center:实现垂直方向居中
  • 重点:父容器必须有明确的高度(比如示例里的height:200px),不然容器高度会被h2内容撑开,没有多余空间来实现垂直居中。

方案2:用内边距模拟垂直居中(无固定高度场景)

如果不想给父容器设固定高度,可以给h2添加上下内边距,用Bootstrap的间距类来快速实现:

<div class="col-4">
    <h2 class="text-center py-5">Text here</h2>
</div>

py-5会给h2添加上下方向的内边距,视觉上达到类似垂直居中的效果,适合容器高度随内容变化的场景。

内容的提问来源于stack exchange,提问作者verts.online

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:45:56