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

父元素设max-height且子元素溢出时,如何让.col占满.container高度?

问题:如何让.col元素占满.container的高度?

现有如下布局代码:

.wrapper {
  max-height: 300px;
  display: flex;
}

.container {
  flex-grow: 1;
  display: flex;
  overflow-y: auto;
  overflow-x: hidden;
  gap: 10px;
}

.col {
  display: flex;
  flex-direction: column;
  flex: 1;
  gap: 10px;
  background-color: blue;
}

.child {
  height: 100px;
  min-height: 100px;
  background: rgba(189, 66, 66, 0.226);
}
<div class="wrapper">
  <div class="container">
    <div class="col">
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
    </div>
    <div class="col">
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
      <div class="child"></div>
    </div>
  </div>
</div>

当前.col元素高度由内部子元素撑开,未能占满.container的高度,以下是两种解决方案:

方案一:让.col占满.container高度,滚动仍由.container控制

直接给.col添加height: 100%,使其继承.container的高度:

.wrapper {
  max-height: 300px;
  display: flex;
}

.container {
  flex-grow: 1;
  display: flex;
  overflow-y: auto;
  overflow-x: hidden;
  gap: 10px;
}

.col {
  display: flex;
  flex-direction: column;
  flex: 1;
  gap: 10px;
  background-color: blue;
  height: 100%; /* 新增:让col高度继承父容器 */
}

.child {
  height: 100px;
  min-height: 100px;
  background: rgba(189, 66, 66, 0.226);
}

方案二:让.col内部独立滚动

如果希望每个.col内部的子元素超出高度时自行滚动,而非让.container整体滚动,可调整如下:

.wrapper {
  max-height: 300px;
  display: flex;
}

.container {
  flex-grow: 1;
  display: flex;
  overflow-x: hidden;
  gap: 10px;
  /* 移除container的overflow-y:auto,交给col处理 */
}

.col {
  display: flex;
  flex-direction: column;
  flex: 1;
  gap: 10px;
  background-color: blue;
  height: 100%; /* 占满container高度 */
  overflow-y: auto; /* 新增:col内部内容超出时滚动 */
}

.child {
  height: 100px;
  min-height: 100px;
  background: rgba(189, 66, 66, 0.226);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 20:09:55