无JavaScript实现两列动态高度布局:子元素高度匹配与滚动需求
问题
需要实现以下布局效果(仅用CSS/Flex,禁止JavaScript):
- 父容器为两列一行布局
- 左侧child1的内容高度决定整个父容器的最大高度
- 右侧child2高度始终与child1保持一致;若child2内部内容高度超过该高度,内部的
.timeslots区域需支持纵向滚动
尝试过Grid布局及变体,但child2总是被内容纵向拉伸,无法实现内部滚动,且所有元素高度均为动态,不能设置固定高度。
用户尝试的代码:
.parent { display: grid; grid-template-columns: auto 1fr; align-items: start; } .child1 { background: #ddd; padding: 1rem; } .child2 { background: #eee; padding: 1rem; max-height: 100%; overflow: hidden; display: flex; flex-direction: column; } .timeslots { overflow-y: auto; flex: 1 1 auto; }
<div class="parent"> <div class="child1"> Tall content here (sets height)<br> Tall content here (sets height)<br> Tall content here (sets height)<br> </div> <div class="child2"> <div class="timeslots"> Lots of scrollable content here...<br> Lots of scrollable content here...<br> Lots of scrollable content here...<br> Lots of scrollable content here...<br> Lots of scrollable content here...<br> Lots of scrollable content here...<br> Lots of scrollable content here...<br> Lots of scrollable content here...<br> </div> </div> </div>
解决方案
使用Grid布局+嵌套Flex即可实现需求,核心是让父容器高度由child1决定,同时给child2设置height: 0; min-height: 100%;来强制它继承父容器的高度约束,避免被内容撑开。修改后的代码如下:
.parent { display: grid; grid-template-columns: auto 1fr; /* 让父容器高度完全由child1的内容决定 */ height: fit-content; } .child1 { background: #ddd; padding: 1rem; } .child2 { background: #eee; padding: 1rem; /* 关键:用height:0+min-height:100%强制继承父容器高度,拒绝被内容撑开 */ height: 0; min-height: 100%; display: flex; flex-direction: column; overflow: hidden; } .timeslots { flex: 1; overflow-y: auto; }
<div class="parent"> <div class="child1"> Tall content here (sets height)<br> Tall content here (sets height)<br> Tall content here (sets height)<br> </div> <div class="child2"> <div class="timeslots"> Lots of scrollable content here...<br> Lots of scrollable content here...<br> Lots of scrollable content here...<br> Lots of scrollable content here...<br> Lots of scrollable content here...<br> Lots of scrollable content here...<br> Lots of scrollable content here...<br> Lots of scrollable content here...<br> </div> </div> </div>
原理说明
- 父容器设置
height: fit-content,确保高度完全由child1的内容决定,不受child2内容影响 - child2的
height: 0强制它放弃自身内容高度的计算,min-height: 100%让它必须占满父容器的高度(即child1的高度) - 嵌套的Flex布局让
.timeslots自动填充child2的剩余空间,超出部分触发纵向滚动
内容的提问来源于stack exchange,提问作者Musaffar Patel
相关产品推荐
相关产品推荐

