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

Flex子元素按需占用空间与滚动功能实现技术问询

解决方案

核心逻辑

通过Flex布局的属性组合,配合尺寸约束规则,精准控制两种场景下子元素的空间分配与滚动行为:

  • 小尺寸元素固定自身高度,不参与空间分配,内容无滚动
  • 大尺寸元素根据同伴类型,自动适配剩余空间或平分容器高度,内容超出时滚动

实现代码

CSS 代码

.flex-container {
  height: 100px;
  width: 100px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin: 10px;
  display: inline-block;
}

/* 基础子元素样式 */
.child {
  overflow: auto;
}

/* 小尺寸子元素规则 */
.child.small-child {
  flex: 0 0 auto; /* 固定自身高度,不扩展不收缩 */
  overflow: visible; /* 内容不滚动 */
}

/* 大尺寸子元素规则 */
.child.large-child {
  flex: 1; /* 单一大元素时占据剩余空间 */
  min-height: 50%; /* 两个大元素时至少占容器50%高度 */
  max-height: 50%; /* 两个大元素时最多占容器50%高度 */
}

.small {
  background: red;
  height: 30px;
}

.large {
  background: blue;
  height: 110px;
}

HTML 代码

<!-- 小-大场景 -->
<div class="flex-container">
  <div class="child small-child">
    <div class="small">Small</div>
  </div>
  <div class="child large-child">
    <div class="large">Large</div>
  </div>
</div>

<!-- 大-大场景 -->
<div class="flex-container">
  <div class="child large-child">
    <div class="large">Large 1</div>
  </div>
  <div class="child large-child">
    <div class="large">Large 2</div>
  </div>
</div>

细节说明

  • 小尺寸子元素通过flex: 0 0 auto锁定自身高度,避免被压缩或强制拉伸,同时关闭滚动确保内容完整展示
  • 大尺寸子元素利用flex:1在搭配小元素时自动填充剩余空间,min-height和max-height的组合则强制两个大元素平分容器高度,超出内容通过overflow:auto触发滚动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 12:57:36