如何在Bootstrap列(column)内实现文本水平垂直居中并消除多余间距
问题原因
- 未配置垂直居中规则:当前仅给内部div添加
mx-auto实现水平居中,未给右侧col-8列设置垂直居中属性,且右侧列默认高度为内容自身高度,没有和左侧图片高度对齐,无法实现垂直居中效果。 - 多余间距为Bootstrap栅格默认属性导致:Bootstrap的
row默认带左右负边距(gutter)、col-*类默认带左右内边距,未主动清除的情况下就会产生多余间隙。
修正后代码
<div class="container-fluid p-0"> <div class="row g-0"> <div class="col-4"> <img src="images/5.png" class="img-fluid w-100" alt="舞蹈宣传图"> </div> <div class="col-8 bg-primary text-white text-center d-flex align-items-center justify-content-center h-100"> <div> <h1>AMAZING DANCE</h1> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. <br> Corrupti perferendis cumque a provident? Ipsam, architecto?</p> <a href="#" class="btn btn-dark btn-lg">READ MORE</a> </div> </div> </div> </div>
核心修改说明
- 清除多余间距:给
container-fluid添加p-0清除默认内边距,row添加g-0清除栅格列默认间隙,彻底消除多余留白。 - 实现双向居中:给右侧
col-8添加d-flex启用弹性布局,align-items-center实现子元素垂直居中,justify-content-center实现子元素水平居中,h-100保证列高度和左侧图片高度一致。 - 图片适配优化:给图片添加
w-100保证图片铺满左侧列,避免出现宽度不足的留白。
内容的提问来源于stack exchange,提问作者Trayansh Agarwal
相关产品推荐
相关产品推荐

