使用Bootstrap的d-flex align-items-center垂直居中后内容左偏求助
解决Bootstrap垂直居中后内容左偏的问题
问题场景:使用d-flex align-items-center h-100实现标题和按钮垂直居中后,内容虽垂直居中但略微向左偏移。
问题原因
你给.container添加了d-flex和h-100使其成为垂直居中的flex容器,但flex容器默认的水平对齐方式是flex-start(靠左对齐),所以内部的.row没有被水平居中,导致整体内容左偏。
解决方案
给外层的.container添加justify-content-center类,这个类会让flex容器的子元素在水平方向上居中对齐,配合align-items-center就能实现水平+垂直双居中。
修改后的核心代码:
<div class="container d-flex align-items-center justify-content-center h-100"> <div class="row"> <header class="text-center col-12"> <h1 class="text-uppercase"><strong>The biggest startup event of the year</strong></h1> </header> <section class="text-center col-12"> <hr> <button class="btn btn-primary btn-xl">Find out more</button> </section> </div> </div>
补充说明
align-items-center负责垂直方向的居中justify-content-center负责水平方向的居中- 确保
html和body也设置了height: 100%(如果自定义样式里没加的话需要补充),否则.container的h-100无法占满整个视口高度:
html, body { height: 100%; margin: 0; }
内容的提问来源于stack exchange,提问作者adam fogel
相关产品推荐
相关产品推荐

