为什么我在Bootstrap flex网格中设置的内容无法正常居中?
问题核心原因
- flex 布局下水平居中生效属性是
justify-content-center,你误用了仅grid布局生效的justify-items-center,导致水平居中不生效 - 高度为90vh的
.eh-intro容器没有设置为flex容器,内部元素无法继承flex对齐规则 - 左列内部存在无样式的冗余嵌套div,打断了flex布局的上下文传递
修改后可直接运行的代码
CSS(和原有代码一致,无需调整)
.eh-height-nav { background-color: blueviolet; height: 150px; } .eh-intro-height0 { background-color: rgb(173, 134, 209); height: 100vh; color: rgb(255, 255, 255); } .eh-intro { width: 100%; height: 90vh; } .eh-intro-img { background-color: rgb(34, 10, 10); height: 300px; width: 300px; color: blanchedalmond; } .eh-intro-columns { width: 100% }
HTML(仅调整类属性、删除冗余嵌套)
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <div class="container-fluid eh-intro-height0 d-flex align-items-center"> <div class="d-flex eh-intro-columns justify-content-center align-items-center"> <div class="eh-intro border mx-4 d-flex justify-content-center align-items-center"> <div class="eh-intro-img"></div> </div> <div class="eh-intro border mx-4 d-flex justify-content-center align-items-center"> Content Img </div> </div> </div>
修改后左右两列内容都会在各自90vh高的容器内实现垂直+水平居中,完全匹配设计稿效果。
内容的提问来源于stack exchange,提问作者SwimLeft
相关产品推荐
相关产品推荐

