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

如何为带滚动条的元素内的子元素添加独立滚动条?

解决模态框内区域独立滚动(适配vh相对高度)

这个问题我太熟悉了!因为容器用了30vh这种相对高度,没法给右侧区域写死固定高度,咱们用Flexbox就能完美解决——核心是让容器内部布局自动分配可用空间,不用硬算高度。

修改后的代码实现

CSS

.container {
  max-height: 30vh;
  border: 1px solid black;
  overflow-x: hidden;
  /* 关键:把容器改成垂直方向的flex布局 */
  display: flex;
  flex-direction: column;
}

.header {
  border: 1px solid red;
  /* 让header只占自身内容高度,避免被压缩 */
  flex-shrink: 0;
}

.body {
  display: flex;
  /* 关键:让body占满容器剩下的所有高度 */
  flex: 1;
  /* 隐藏超出部分,确保内部滚动区域正常工作 */
  overflow: hidden;
}

.leftArea {
  border: 1px solid green;
  width: 50%;
  flex-shrink: 0;
}

.rightArea {
  border: 1px solid blue;
  width: 50%;
  overflow-x: hidden;
  overflow-y: auto;
  /* 不需要硬写height了! */
}

HTML

<div class="container">
  <div class="header"> HEADER </div>
  <div class="body">
    <div class="leftArea">
      <p>left area</p>
      <p>left area</p>
      <p>left area</p>
      <p>left area</p>
      <p>left area</p>
      <p>left area</p>
      <p>left area</p>
      <p>left area</p>
      <p>left area</p>
    </div>
    <div class="rightArea">
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
      <p>right area</p>
    </div>
  </div>
</div>

关键原理说明

  • 容器的Flex布局:给.container设置flex-direction: column后,内部的.header和.body会垂直排列,.body通过flex:1自动占据容器中除了.header之外的所有剩余高度,完美适配30vh的相对高度。
  • body的overflow:hidden:这一步很重要,能确保内部的.rightArea在内容超出时只会自己滚动,不会触发整个容器的滚动。
  • header的flex-shrink:0:防止header在容器高度变小时被压缩,保持自身的内容高度。

这样修改后,不管容器是30vh还是其他相对高度,右侧区域都能自动获得可用高度,内容超出时显示独立滚动条,完全不用硬写固定高度!

内容的提问来源于stack exchange,提问作者Metarat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:23:27