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

如何在div中实现文本垂直与水平居中?Bootstrap代码求助

解决h1垂直水平居中的问题

你的h1已经通过text-center实现了水平居中,但垂直居中未生效——核心原因是父容器(section及外层div)没有设置足够高度和垂直对齐的布局规则。以下是基于Bootstrap的两种实用解决方案:

方案1:让内容在视口内垂直水平居中(常用场景)

给section添加Bootstrap的flex布局类和高度类,直接让内容占满视口并居中:

修改后的完整代码:

<div>
  <section id='vision' class="min-vh-100 d-flex align-items-center justify-content-center">
    <div className="container">
      <div className="row justify-content-center">
        <div className="col-md-8">
          <h1 className="display-4 fw-bolder mb-4 text-center text-white">History</h1>
        </div>
      </div>
    </div>
  </section>
</div>
  • min-vh-100:让section高度至少占满整个视口
  • d-flex:将section设为flex容器
  • align-items-center:垂直方向居中对齐子元素
  • justify-content-center:水平方向居中对齐子元素
  • 移除了mt-5,避免额外margin干扰居中效果

方案2:固定高度容器内居中

如果不需要占满视口,只需在固定高度的容器内居中,可给section设置固定高度(比如h-75),再搭配flex类:

<section id='vision' class="h-75 d-flex align-items-center justify-content-center">

核心原理

实现垂直居中必须满足两个条件:

  1. 父容器有明确高度(要么占满视口,要么设置固定高度)
  2. 父容器启用flex布局,并通过align-items: center实现垂直对齐(Bootstrap的align-items-center已封装该CSS属性)

内容的提问来源于stack exchange,提问作者ThatGuyNick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:11:02