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

在Bootstrap中仅对单个flex项内的文本实现垂直居中对齐

解决方法

你之前用align-items-center和align-self-center没生效,是因为这两个类控制的是flex子项在父容器交叉轴上的对齐位置,不是区块内部内容的对齐规则。要实现第二个区块内文本单独垂直居中,只需要把第二个区块本身设置为flex容器,再开启交叉轴居中即可,完全用Bootstrap内置工具类就能实现,不需要额外写自定义样式。

修改后的完整代码如下:

<div class="card" style="width: 350px; height: 250px;">
  <div class="card-body">
    <div class="d-flex flex-column" style="height: 100%;">
      <div class="p-2" style="height: 30%">1</div>
      <!-- 仅给第二个区块加d-flex和align-items-center类 -->
      <div class="p-2 d-flex align-items-center" style="height: 50%;">2</div>
      <div class="p-2" style="height: 20%">3</div>
    </div>
  </div>
</div>

原理解释

  • 给第二个区块加d-flex:将这个区块本身转为flex布局容器
  • 加align-items-center:让容器内的直接子元素(这里就是文本内容)在交叉轴(垂直方向)居中对齐
  • 另外两个区块没有加对应的类,样式不受任何影响,完全符合需求。该方案适配性强,即使第二个区块内的文本出现换行也能保持垂直居中效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:27:04