一个会拉伸、却会滚动的DIV?

前端开发 2026-07-09

我想做一个 <div>,它能够在其父元素 <div> 内填满所有可用的垂直空间;但当它因为内部内容(如图片,或文本滚动)而超过该父元素 <div> 的高度时,仍然保持自适应高度。

到目前为止,我已经尝试了在别处看到的 min-height: 0; flex: 1; overflow-y: auto; 技巧,但似乎并没有奏效。下面是我迄今为止所做的示例代码。

它不是让内容滚动,而是继续增大,越过左边列所设定的边界。

.box {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  border: 1px solid #000;
  padding: 0.5em;
}

.inner {
  flex: 1;               
  overflow-y: scroll;     
  min-height: 0;
  border: 1px solid #000;
  padding: 0.5em;
}

.row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 0.5em;
}

.col {
  display: flex;
  flex: 1;
  flex-direction: column;
  flex-wrap: wrap;
  gap: 0.5em;
  border: 1px solid #000;
  padding: 0.5em;
}
<div class="row">
  <div class="col">
    <div class="box">
      text. <br><br> text. <br><br> text. <br><br> text. <br><br>
    </div>
  </div>
  <div class="col">
    <div class="box">
      <div class="inner">
        text. <br><br>text. <br><br>text. <br><br>text. <br><br>text. <br><br>
      </div>
    </div>
  </div>
</div>

解决方案

为什么不在父级使用 position:relative,在子级使用 position:absolute,让它填满空间呢? 不过我认为你必须为其中一个父级设置高度。

.box {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  border: 1px solid #000;
  padding: 0.5em;
}

.inner {
  flex: 1;
  overflow-y: scroll;
  min-height: 0;
  border: 1px solid #000;
  padding: 0.5em;
}

.row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 0.5em;
}

.col {
  display: flex;
  flex: 1;
  flex-direction: column;
  flex-wrap: wrap;
  gap: 0.5em;
  border: 1px solid #000;
  padding: 0.5em;
}


/* Changes are below */

.col {
  position: relative;
  height: 175px;
}

.box {
  position: absolute;
  top: 10px;
  bottom: 10px;
  overflow-y: auto;
}
<div class="row">
  <div class="col">
    <div class="box">
      text. <br><br> text. <br><br> text. <br><br> text. <br><br>
      text. <br><br> text. <br><br> text. <br><br> text. <br><br>

    </div>
  </div>
</div>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章