如何让Flexbox中可滚动Div占据剩余空间?
实现Flex布局下可滚动且优先压缩的容器
需求说明
需要达成以下布局效果:
.orange容器内容过多时可垂直滚动- 屏幕高度缩小时,
.orange优先被压缩至min-height: 30px,之后才允许.root的子元素溢出 - 向
.orange添加内容时,不会改变其他元素的尺寸 - 仅通过
flex: 1让.orange占据容器剩余空间,不设置max-height
解决方案
核心修改是给.blue容器添加overflow: hidden,同时保留原有flex属性配置:
.root作为固定高度的flex容器,.blue通过flex: 1填充剩余空间,但默认flex容器不会限制内部子项的高度溢出,添加overflow: hidden后可以约束.blue内部元素的高度范围,确保.orange只能在.blue的可用空间内伸缩.orange的flex: 1会自动占据.blue中除.white固定高度外的剩余空间,min-height: 30px定义了压缩的下限,overflow-y: scroll在内容超出容器高度时触发滚动
修改后的代码
CSS
.root { height: 70vh; display: flex; flex-direction: column; } .blue { display: flex; flex-direction: column; flex: 1; overflow: hidden; /* 关键新增属性 */ } .white { height: 50px; } .orange { flex: 1; min-height: 30px; overflow-y: scroll; } /* ________________STYLING_______________ */ .root { width: 300px; border: 3px solid red; } .blue { border: 5px solid blue; } .white { background-color: grey; border: 3px solid white; } .orange { background-color: lightgrey; border: 3px solid orange; } p { margin: 0; padding: 0; }
HTML
<div class="root"> <div class="blue"> <div class="white"> I have fixed height (panel) </div> <div class="orange"> <p>I have a minimum height</p> <p>And I can scroll</p> <p>And I can scroll</p> <p>And I can scroll</p> <p>And I can scroll</p> </div> </div> </div>
内容的提问来源于stack exchange,提问作者713sean
相关产品推荐
相关产品推荐

