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

如何在Bootstrap 5的col类div中垂直对齐文本内容?

Bootstrap 5 列内文本垂直对齐解决方法

你遇到的问题是因为 align-middle 类需要作用在 flex子元素 上,但默认情况下 col 是块级容器,不是flex容器,所以直接加这个类不会生效。要实现列内文本垂直对齐,需要两步:

  1. 给目标 col 添加 d-flex 类,将其转为flex容器
  2. 根据需求添加 align-items-center(垂直居中)、justify-content-center(水平居中)这类flex对齐类

另外,建议用Bootstrap的 text-center 工具类代替已经废弃的 <center> 标签,更符合现代HTML规范。

修改后的完整代码:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div class="container">
  <br>
  <div class="row">
    <div class="col" style="background-color:#cbedca;">
      <div class="text-center" style="margin-top:80px;margin-bottom:80px;">
        <h3>Ocean pollution is a massive environmental crisis.</h3>
        There is currently over 5.25 trillion macro and micro pieces of plastic in our oceans. Plastic bottles are a single-use plastic, meaning they are a product designed to be used only once and then discarded. CODi is committed to giving back to the environment
        in any way we can.
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-6">
      <img src="https://cdn.shopify.com/s/files/1/0615/5403/2853/files/CODi_TerraPlasticBottles.png?v=1664543910" style="width:100%;">
    </div>
    <div class="col d-flex align-items-center justify-content-center" style="background-color:#d9f4ff;line-height:1em;">
      <div class="text-center">
        Made from
        <br><b style="font-size:3em;line-height:1em">30</b>
        <br><b>OCEAN-BOUND
          <br>PLASTIC BOTTLES</b>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-6">
      <img src="https://cdn.shopify.com/s/files/1/0615/5403/2853/files/CODi_PlasticBottles1.png?v=1664550375" style="width:100%">
    </div>
    <div class="col d-flex align-items-center">
      <div>
        <h4>Every day around 8 million pieces of plastic makes their way into our oceans.</h4>
        Once in the ocean, a single-use bottle moves with the currents of the wind and the ocean and can take <b>hundreds of years to break down into microplastic</b>.
      </div>
    </div>
  </div>

</div>

关键修改点:

  • 第二个row的右侧col添加了 d-flex align-items-center justify-content-center,实现内部内容垂直+水平居中
  • 第三个row的右侧col添加了 d-flex align-items-center,实现内容垂直居中
  • 所有<center>标签替换为 text-center 类

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:10:52