You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 19:15:51