Bootstrap 4:如何设置窄文本居中布局且保持标题段落垂直排列?
解决Bootstrap布局中宽度改为50%时保持垂直居中排列的问题
我懂你遇到的困扰——Bootstrap的row默认是弹性布局,主轴方向是横向的,直接把标题和段落丢进去加w-50,它们就会并排显示;调整flex方向成垂直后,又容易出现内容左对齐的情况。这里有两个简单可行的解决办法:
方法一:调整row的flex属性
直接给row添加flex-column(让子元素垂直排列)和align-items-center(让子元素水平居中)类,再把段落的w-75改成w-50即可:
<div class="container"> <div class="row justify-content-center flex-column align-items-center"> <h3 class="pt-5 pb-3">How can ExampleSite help you?</h3> <p class="feature-summary w-50"> With us, not only can you find a great deal, but should your prices go up or something better come on the market we can find it automatically. </p> </div> </div>
flex-column:把row的主轴方向从横向改成纵向,标题和段落自然会上下垂直排列align-items-center:让每个子元素在水平方向上居中对齐,避免内容左偏- 保留
justify-content-center可以让内容在垂直方向上也居中(如果容器有足够高度的话),不需要的话也可以直接去掉
方法二:用col包裹内容
另一种思路是把标题和段落放进一个col容器里,给这个col设置w-50和mx-auto(左右margin自动,实现水平居中),内部元素会自然垂直排列:
<div class="container"> <div class="row"> <div class="col w-50 mx-auto"> <h3 class="pt-5 pb-3 text-center">How can ExampleSite help you?</h3> <p class="feature-summary"> With us, not only can you find a great deal, but should your prices go up or something better come on the market we can find it automatically. </p> </div> </div> </div>
mx-auto让col在row中水平居中,w-50限制宽度为50%- 给标题加
text-center可以让标题和段落对齐居中,不需要的话可以去掉这个类
这两种方法都能实现你想要的效果,选哪种看你后续的布局扩展需求就好~
内容的提问来源于stack exchange,提问作者Yunti
相关产品推荐
相关产品推荐

