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

如何让可纵向拉伸的flex容器内实现垂直滚动?

解决flex子元素内部独立滚动问题

问题核心是flex容器的默认特性导致的:当内部内容高度超过容器分配空间时,flex容器会自动扩展高度容纳内容,最终让外层.all-except-navbar超出视口,触发页面全局滚动条。只需修改两处CSS即可解决:

具体修改点

  • 给.greedy-div添加overflow: hidden:强制这个flex容器严格遵守分配的高度,不被内部内容撑开,为子元素的滚动提供固定高度边界。
  • 优化.div-that-needs-to-scroll的滚动属性:将overflow: auto; overflow-y:scroll;简化为overflow-y: auto,仅在内容超出时显示滚动条,交互更合理。

修改后的完整CSS代码

body, html {
  margin: 0;
  padding: 0;
}
.navbar {
   height: 70px;
   width: 100%;
   background-color: red;
}
.all-except-navbar {
  height: calc(100vh - 70px);
  width: 100%;
  display: flex;
  flex-direction: column;
}
.chill-div {
  width: 100%;
  background-color: blue;
}
.greedy-div {
  width: 100%;
  background-color: green;
  flex: 1;
  overflow: hidden; /* 新增:限制容器高度,避免被内容撑开 */
}
.the-parent {
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: pink;
}
.left-child {
  height: 100%;
  width: 35.5%;
  background-color: pink;
}
.right-child {
  height: 100%;
  width: 64%;
  background-color: grey;
}
.div-that-needs-to-scroll {
  background-color: yellow;
  width: 100%;
  height: 100%;
  overflow-y: auto; /* 优化:仅内容超出时显示滚动条 */
}

原理说明

.greedy-div作为flex:1的子元素,原本会因内部内容溢出自动拉伸高度,添加overflow:hidden后,它的高度被固定在.all-except-navbar分配的剩余空间内。此时.div-that-needs-to-scroll的height:100%有了明确参考高度,内容超出时会在自身容器内触发滚动,不会影响整个页面。

内容的提问来源于stack exchange,提问作者Uzair A.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:35:51