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

使用Bootstrap在HTML中无法实现垂直居中的问题排查

.box元素无法垂直居中的原因及解决方法

你当前的代码无法实现.box垂直居中,核心原因是承载col的row元素没有占满父容器的高度,导致align-items-center没有生效的空间。

具体原因分析

  • 你的蓝色父容器设置了height:250px,但内部的row元素默认高度由内容(.box)撑开,高度和.box完全一致。
  • align-items-center的作用是让flex容器(这里的row)的子元素(col)在容器的垂直方向上居中,但因为row本身高度和col高度相同,所以完全看不到居中效果。

解决方法

提供两种可行方案,可根据你的布局需求选择:

方案1:让父容器成为flex容器,直接让row垂直居中

修改蓝色父容器的代码,添加Bootstrap的d-flex align-items-center类,同时给row添加w-100保证宽度占满父容器:

<div class="d-flex align-items-center" style="height: 250px; background-color: blue;">
    <div class="row justify-content-start w-100">
        <div class="col-4">
            <div class="box">1</div>
        </div>
        <div class="col-4">
            <div class="box">1</div>
        </div>
    </div>
</div>

方案2:让row占满父容器高度,再实现内部col的垂直居中

给row添加h-100类,让它占满父容器的250px高度,这样align-items-center就能让col在row的高度范围内垂直居中:

<div style="height: 250px; background-color: blue;">
    <div class="row d-flex align-items-center justify-content-start h-100">
        <div class="col-4">
            <div class="box">1</div>
        </div>
        <div class="col-4">
            <div class="box">1</div>
        </div>
    </div>
</div>

如果后续给.box设置了固定高度,想要让.box在col内部也垂直居中,可以给col添加d-flex align-items-center类,示例:

<div class="col-4 d-flex align-items-center">
    <div class="box">1</div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:05:25