为何flex-grow容器内的min-height:100%不生效?
解决方法:不修改父容器让蓝色div垂直铺满
问题根源在于:红色父容器是外层flex容器的子项,通过flex-grow:1获得了实际高度,但它没有显式设置height或min-height,导致蓝色子容器的min-height:100%找不到有效的参照高度,只能自适应内容高度。
以下是几种无需修改父容器的可行方案:
方案1:给蓝色div设置height: 100%
直接将蓝色div的min-height:100%替换为height:100%:
<div style="min-height: 100vh; display: flex; flex-direction: column"> <div style="flex-grow: 1; background-color: red;"> <div style="height: 100%; background-color: blue;"> Test </div> </div> </div>
父容器作为flex项,其高度是外层flex容器计算出的确定值,子元素设置height:100%可以直接继承这个计算高度。
方案2:将蓝色div设为flex容器
给蓝色div添加display: flex属性:
<div style="min-height: 100vh; display: flex; flex-direction: column"> <div style="flex-grow: 1; background-color: red;"> <div style="display: flex; background-color: blue;"> Test </div> </div> </div>
flex容器的默认行为是拉伸自身高度以适应父容器的可用空间,无需额外设置高度参数。
方案3:使用fill-available自适应可用空间
给蓝色div设置min-height: fill-available(加上webkit前缀兼容旧版浏览器):
<div style="min-height: 100vh; display: flex; flex-direction: column"> <div style="flex-grow: 1; background-color: red;"> <div style="min-height: -webkit-fill-available; min-height: fill-available; background-color: blue;"> Test </div> </div> </div>
这个属性会让元素自动占满父容器的可用空间,不需要依赖父元素的显式高度设置,非常适合复杂布局场景。
内容的提问来源于stack exchange,提问作者Spook
相关产品推荐
相关产品推荐

