如何在Bootstrap 5的col类div中垂直对齐文本内容?
Bootstrap 5 列内文本垂直对齐解决方法
你遇到的问题是因为 align-middle 类需要作用在 flex子元素 上,但默认情况下 col 是块级容器,不是flex容器,所以直接加这个类不会生效。要实现列内文本垂直对齐,需要两步:
- 给目标
col添加d-flex类,将其转为flex容器 - 根据需求添加
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
相关产品推荐
相关产品推荐

