如何用Flexbox实现Bootstrap 4中元素拉伸至父容器剩余高度?
解决方案:用Flexbox实现Bootstrap列内标题等高且垂直居中
当然可以用Flexbox解决这个问题,而且结合Bootstrap 4的内置Flex类会更省心——毕竟Bootstrap 4本身就是基于Flexbox构建的。你之前的思路方向是对的,只是少了几个关键的设置,我来帮你调整:
核心思路
把每个列(.col-lg-4)变成垂直方向的Flex容器,让标题所在的容器自动填充图片下方的剩余空间,同时让标题在容器内垂直居中,这样不管标题换行与否,所有标题容器的高度都会保持一致。
修改后的代码
HTML部分
关键是给每个.col-lg-4添加d-flex flex-column类,同时给标题的父容器.test补充Flex居中类:
<section id="home_univers"> <div class="container"> <div class="row"> <div class="col-lg-4 d-flex flex-column"> <img alt="Animaux de compagnie" src="http:/placehold.it/450x210"> <div class="test d-flex align-items-center justify-content-center flex-1"> <h3 class="bg_rose">aaaaaaa aa aaaaaaaaa</h3> </div> </div> <!-- /.col-lg-4 --> <div class="col-lg-4 d-flex flex-column"> <img alt="Chevaux" src="http:/placehold.it/450x210"> <div class="test d-flex align-items-center justify-content-center flex-1"> <h3 class="bg_vert">aaaaaaa</h3> </div> </div> <!-- /.col-lg-4 --> <div class="col-lg-4 d-flex flex-column"> <img alt="Animaux de rente" src="http:/placehold.it/450x210"> <div class="test d-flex align-items-center justify-content-center flex-1"> <h3 class="bg_blue">aaaaaaa aa aaaaa</h3> </div> </div> <!-- /.col-lg-4 --> </div> <!-- /.row --> </div> <!-- /.container --> </section>
CSS部分
补充一个自定义的flex-1类(也可以直接用Bootstrap原生的flex-grow-1),同时微调h3的内外边距避免布局挤压:
.blue { color: #0033a0; } .bg_blue { background-color: #0033a0; } .rose { color: #ff7a6d; } .bg_rose { background-color: #ff7a6d; } .vert { color: #8dad20; } .bg_vert { background-color: #8dad20; } #home_univers { padding-top: 85px; padding-bottom: 85px; } #home_univers h3 { text-transform: uppercase; color: #fff; font-size: 24px; text-align: center; padding: 15px; margin: 0; width: 100%; /* 确保标题背景铺满容器宽度 */ } #home_univers img { width: 100%; } /* 自定义类:让容器占据列内剩余空间 */ .flex-1 { flex: 1; }
为什么这样有效?
d-flex flex-column让每个列变成垂直方向的Flex容器,内部的图片和.test会按垂直方向排列;flex-1让.test容器自动填充图片下方的所有剩余空间,三个列的.test高度会完全同步,不受标题行数影响;d-flex align-items-center justify-content-center让标题在.test容器内同时实现水平和垂直居中;- 给h3设置
width:100%是为了让背景色铺满整个容器宽度,避免标题内容短的时候背景只包裹文字区域。
现在你调整屏幕大小试试,不管标题是一行还是多行,三个标题栏的高度都会保持一致,而且文字始终居中~
内容的提问来源于stack exchange,提问作者user8538154
相关产品推荐
相关产品推荐

