使用Bootstrap5实现按钮居中对齐,添加justify-content-center无效如何解决
问题原因
你把justify-content-center加在了外层row上,但是该row的直接子元素是宽度默认占满整行的col容器:
row上的justify-content-center只会作用于它的直接子元素(也就是内部的col),而col本身宽度100%,就算被row居中也不会影响内部按钮的对齐- 两个按钮是
col的直接子元素,默认左对齐,你没有给col设置对齐规则,所以居中不生效
解决方案
提供两种最简单的实现方式,任选一种即可:
方案1:给按钮的父容器col添加文本居中类
因为Bootstrap的btn默认是行内块元素,用text-center类即可控制内部行内/行内块元素居中:
<div class="col-8 offset-2 col-lg-9 col-xl-6 offset-xl-3"> <div class="row"> <h1 class="mt-5">What is this all about. What is this all about. What is this all abour?</h1> </div> <div class="row mt-5"> <div class="col text-center"> <button type="button" class="btn btn-primary m-2">Yes Please</button> <button type="button" class="btn btn-primary">No Please</button> </div> </div> </div>
方案2:将按钮父容器设为弹性容器后居中
给col添加d-flex和justify-content-center类,通过弹性布局规则居中内部按钮:
<div class="col-8 offset-2 col-lg-9 col-xl-6 offset-xl-3"> <div class="row"> <h1 class="mt-5">What is this all about. What is this all about. What is this all abour?</h1> </div> <div class="row mt-5"> <div class="col d-flex justify-content-center"> <button type="button" class="btn btn-primary m-2">Yes Please</button> <button type="button" class="btn btn-primary">No Please</button> </div> </div> </div>
内容的提问来源于stack exchange,提问作者Baba
相关产品推荐
相关产品推荐

