Flex纵向布局中如何根据动态内容自适应管理子元素高度?
问题场景
现有纵向Flex布局父容器高度随窗口动态变化,包含3个子元素,需满足以下布局规则:
- child2承载可动态增减的内容,需完整展示自身内容、不出现滚动条,优先适配内容高度
- child3为固定高度
- child1占据扣除child2、child3高度后的剩余空间,内容溢出时在自身内部展示滚动条
当前编写的存在问题的代码如下:
.parent { display: flex; height: 100%; flex-direction: column; } .child1 { overflow: auto; display: flex; flex-direction: column; background: red; } .child2 { display: flex; flex-direction: column; background: blue; } .child3 { display: flex; flex-direction: column; background: orange; }
<div class="parent"> <div class="child1">data</div> <div class="child2">dynamic data</div> <div class="child3">fixed data</div> </div>
参考效果图:
修复方案
原有代码不生效的核心原因是两点:
- child1没有设置flex伸缩属性,默认不会自动占据父容器的剩余空间
- 纵向Flex布局的子项默认
min-height值为auto,会强制子项高度不小于自身内容高度,导致overflow: auto配置无法触发滚动条
只需要调整child1的样式,同时给child3设置明确的固定高度即可,修正后的完整CSS代码如下:
.parent { display: flex; height: 100%; flex-direction: column; } .child1 { /* 占据父容器扣除其他子元素高度后的所有剩余空间,允许空间不足时收缩 */ flex: 1 1 auto; /* 覆盖默认min-height: auto,允许内容溢出时触发滚动 */ min-height: 0; overflow: auto; display: flex; flex-direction: column; background: red; } .child2 { /* 保持默认flex属性即可,自动适配内容高度,不会被压缩 */ display: flex; flex-direction: column; background: blue; } .child3 { /* 按业务需求设置固定高度,示例值为80px,可自行修改 */ height: 80px; display: flex; flex-direction: column; background: orange; }
样式说明:
- child2无需额外配置flex属性,默认的
flex: 0 1 auto会让它始终根据内容撑开高度,不会被压缩,也不会出现滚动条 - child3设置固定高度后,会始终占据对应尺寸的空间
- child1的两个核心属性配合后,会自动填充剩余高度,内容超出自身高度时就会在内部出现滚动条,不会撑开父容器
内容的提问来源于stack exchange,提问作者Rupinderpal Thind
相关产品推荐
相关产品推荐

