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

如何设置Flex容器最大高度以匹配指定子项并实现滚动效果?

问题与解决方案

现有代码

CSS 代码

.container {
      padding: 10px;
      display: flex;
      width: 80vw;
      justify-content: space-between;
      margin: 0 auto;
      margin-top: 20px;
      background: green;
  }

  .item_1 {
      max-height: 100%;
      /*max-height: 1200px;(it can be >.item_2)*/
      width: 200px;
      overflow-y: scroll;
      background: orange;

  }

  .item_2 {
      height: 800px;
      width: 800px;
      background: orange
  }

HTML 代码

<div>
    <div class='container'>
        <div class='item_1'></div>
        <div class='item_2'></div>
    </div>
</div>

需求说明

  • 将.container(绿色容器)的max-height设置为与.item_2(橙色固定高度子项)的高度一致;
  • 当.item_1的高度大于.item_2时,为.item_1添加垂直滚动条;
  • 当.item_1的高度小于等于.item_2时,保持两个子项高度一致。

效果示意图

实现方案

直接调整CSS即可达到需求,修改后的代码如下:

修改后的CSS代码

.container {
  padding: 10px;
  display: flex;
  width: 80vw;
  justify-content: space-between;
  margin: 0 auto;
  margin-top: 20px;
  background: green;
  /* 让容器高度自适应子项,同时最大高度和item_2保持一致 */
  height: fit-content;
  max-height: 800px;
}

.item_1 {
  width: 200px;
  background: orange;
  /* 默认和容器高度对齐,内容超出时显示滚动条 */
  height: 100%;
  overflow-y: auto;
}

.item_2 {
  height: 800px;
  width: 800px;
  background: orange;
}

核心逻辑

  1. 给.container设置max-height: 800px(和.item_2的固定高度匹配),同时用height: fit-content确保容器在.item_1内容较少时,高度自动收缩到和子项一致;
  2. .item_1设置height: 100%,这样内容不多时会和容器(也就是.item_2)高度完全对齐;
  3. overflow-y: auto替代原有的scroll,只有当.item_1内容高度超过容器最大高度时才显示滚动条,避免无内容时出现空滚动条。

如果要避免硬写高度值,方便后续维护,可以用CSS变量统一管理:

:root {
  --fixed-item-height: 800px;
}

.container {
  /* ...其他样式 */
  height: fit-content;
  max-height: var(--fixed-item-height);
}

.item_2 {
  height: var(--fixed-item-height);
  /* ...其他样式 */
}

这样后续修改.item_2高度时,只需要更新--fixed-item-height的值即可,不用多处调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:45:37