父容器设max-height时,如何实现子div动态滚动?
实现自适应高度且带最大高度限制的滚动侧边面板(纯CSS方案)
完全可以用纯CSS解决这个需求,不需要借助JavaScript。问题的核心是百分比高度在父元素仅设置max-height时无法正确计算,导致内部flex容器无法限制高度,进而让滚动容器无法触发滚动。
关键修改方案
调整父容器和flex容器的布局属性,让容器既能自适应内容高度,又能在达到最大高度后触发内部滚动:
- 给
.parent-container添加display: flex和flex-direction: column,使其高度由内容决定,同时受max-height约束 - 移除
.flex-container的height: 100%,改为让它自动填充父容器的可用空间 - 给
.scrolling-container添加min-height: 0,打破flex子元素默认的最小高度限制,确保内容溢出时能收缩并触发滚动
修改后的完整代码
* { box-sizing: border-box; } .parent-container { width: 250px; border: 1px solid black; display: inline-flex; /* 修改为inline-flex,保持横向排列 */ flex-direction: column; max-height: 500px; margin-right: 20px; /* 增加间距区分两个容器 */ } .flex-container { display: flex; flex-direction: column; flex: 1; /* 让flex容器填充父容器的可用空间 */ } .scrolling-container { flex: 1; overflow-y: auto; min-height: 0; /* 关键:允许滚动容器在内容过多时收缩 */ } .item { height: 100px; width: 100px; background: red; margin: 5px; }
<div class="parent-container"> <div class="flex-container"> <div> This box should hit the max height and start scrolling the inner div </div> <div class="scrolling-container"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <div>This div stays on bottom</div> </div> </div> <div class="parent-container"> <div class="flex-container"> <div> This container shouldn't scroll and should only be as tall as the content </div> <div class="scrolling-container"> <div class="item"></div> <div class="item"></div> </div> <div>This div stays on bottom</div> </div> </div>
效果说明
- 左侧容器:内容高度超过
max-height:500px时,.scrolling-container会自动出现垂直滚动条,底部的固定内容保持在面板底部 - 右侧容器:内容高度未达到最大高度,面板会自适应内容高度,不会出现滚动条
内容的提问来源于stack exchange,提问作者Patrick Son
相关产品推荐
相关产品推荐

