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

为何Bootstrap Row容器内文本无法垂直居中?求解决方案

Bootstrap row容器内文本垂直居中问题解决

我使用Bootstrap的row容器布局时,尝试让文本同时实现水平与垂直居中,但目前仅能实现水平居中,垂直方向未达到预期效果。

当前效果:
错误效果

预期效果:
正确效果

第二张图中“contact me”文本在容器内同时实现了水平和垂直居中。

我的HTML代码:

<div class="col-lg-6">
    <h1 class="landing-header">PLACEHOLDER</h1>
    <p class="landing-text">PLACEHOLDLER</p>

    <div class="row landing-contact-me">
        <div class="col-2">
            <a href="linkedin.com">
                <img class="img-fluid landing-socials" src="assets/linkedin.png">
            </a>
        </div>
        <div class="col-2">
            <a href="instagram.com">
                <img class="img-fluid landing-socials" src="assets/instagram.png">
            </a>
        </div>
        <div class="col-8 center">
            <p id="landing-contact-me-text">contact me</p>
        </div>
    </div>
</div>

我尝试使用自定义.center类,但并未生效。

相关CSS代码:

.landing-header {
    font-family: 'DM Serif Display';
    font-size: 4rem;
}

.landing-text {
    font-family: 'Montserrat';
    font-size: 1.25rem;
    font-weight: 200;
    margin-right: 25%;
    text-align: justify;
}

.landing-contact-me {
    margin-top: 30%;
    margin-right: 25%;
    padding: 3% 2% 3% 2%;
    border-radius: 25px;
    background-color: white;
    box-shadow: 0px 0px 90px rgba(0, 0, 0, 0.1);
    align-items: center;
    text-align: center;
}

.landing-socials {
    max-width: 100%;
    height: auto;
}

#landing-contact-me-text {
    font-family: 'Montserrat';
    font-size: 1.25rem;
    font-weight: 200;
    text-align: center;
}

.center {
    text-align: center;
    vertical-align: middle;
}

解决方案

问题核心在于:你给row添加的align-items: center是让row的子元素(col)整体垂直对齐,但“contact me”文本所在的col内部,文本并没有垂直居中;另外vertical-align: middle仅对行内元素或表格单元生效,对普通块级元素无效。

推荐以下两种方法解决:

方法1:使用Bootstrap内置flex工具类

直接给包含文本的col添加Bootstrap的flex工具类,无需自定义CSS:

<div class="col-8 d-flex align-items-center justify-content-center">
    <p id="landing-contact-me-text">contact me</p>
</div>
  • d-flex:将元素设置为flex容器
  • align-items-center:实现内部元素垂直居中
  • justify-content-center:实现内部元素水平居中

方法2:修改自定义.center类的CSS

如果要保留自定义类,更新.center的样式:

.center {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%; /* 确保col占满父row的高度 */
}

该方法通过flex布局让文本在col内居中,同时设置height:100%确保col高度与其他列一致。


内容的提问来源于stack exchange,提问作者Adam A.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:25:21