如何在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">
核心原理
实现垂直居中必须满足两个条件:
- 父容器有明确高度(要么占满视口,要么设置固定高度)
- 父容器启用flex布局,并通过
align-items: center实现垂直对齐(Bootstrap的align-items-center已封装该CSS属性)
内容的提问来源于stack exchange,提问作者ThatGuyNick
相关产品推荐
相关产品推荐

