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

无JavaScript实现两列动态高度布局:子元素高度匹配与滚动需求

问题

需要实现以下布局效果(仅用CSS/Flex,禁止JavaScript):

  • 父容器为两列一行布局
  • 左侧child1的内容高度决定整个父容器的最大高度
  • 右侧child2高度始终与child1保持一致;若child2内部内容高度超过该高度,内部的.timeslots区域需支持纵向滚动

尝试过Grid布局及变体,但child2总是被内容纵向拉伸,无法实现内部滚动,且所有元素高度均为动态,不能设置固定高度。

用户尝试的代码:

.parent {
  display: grid;
  grid-template-columns: auto 1fr;
  align-items: start;
}

.child1 {
  background: #ddd;
  padding: 1rem;
}

.child2 {
  background: #eee;
  padding: 1rem;
  max-height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.timeslots {
  overflow-y: auto;
  flex: 1 1 auto;
}
<div class="parent">
  <div class="child1">
    Tall content here (sets height)<br>
    Tall content here (sets height)<br>
    Tall content here (sets height)<br>
  </div>
  <div class="child2">
    <div class="timeslots">
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
    </div>
  </div>
</div>
解决方案

使用Grid布局+嵌套Flex即可实现需求,核心是让父容器高度由child1决定,同时给child2设置height: 0; min-height: 100%;来强制它继承父容器的高度约束,避免被内容撑开。修改后的代码如下:

.parent {
  display: grid;
  grid-template-columns: auto 1fr;
  /* 让父容器高度完全由child1的内容决定 */
  height: fit-content;
}

.child1 {
  background: #ddd;
  padding: 1rem;
}

.child2 {
  background: #eee;
  padding: 1rem;
  /* 关键:用height:0+min-height:100%强制继承父容器高度,拒绝被内容撑开 */
  height: 0;
  min-height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.timeslots {
  flex: 1;
  overflow-y: auto;
}
<div class="parent">
  <div class="child1">
    Tall content here (sets height)<br>
    Tall content here (sets height)<br>
    Tall content here (sets height)<br>
  </div>
  <div class="child2">
    <div class="timeslots">
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
      Lots of scrollable content here...<br>
    </div>
  </div>
</div>

原理说明

  1. 父容器设置height: fit-content,确保高度完全由child1的内容决定,不受child2内容影响
  2. child2的height: 0强制它放弃自身内容高度的计算,min-height: 100%让它必须占满父容器的高度(即child1的高度)
  3. 嵌套的Flex布局让.timeslots自动填充child2的剩余空间,超出部分触发纵向滚动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 04:22:43