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

如何用Flexbox实现带两个滚动区域的卡片布局?

实现带双滚动区域的Flexbox卡片

问题描述

需要构建一个带两个滚动区域的卡片,卡片有最大宽高限制:

  • 青色的「Full text」区域内容过长时需垂直滚动
  • 右侧「Thumbnails」区域条目过多时需垂直滚动
    当前使用Flexbox的方案无法让滚动生效,因为无法给滚动区域设置固定高度,希望仅用Flexbox+纯CSS解决。

初始代码

CSS

.card {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 50%;
  min-width: 100px;
  min-height: 0;
  max-width: 80%;
  max-height: 80%;
  border: solid 1px black;
  padding: 10px;
}

.photo {
  background-color: silver;
  margin-bottom: 10px;
  aspect-ratio: 3;
}

.body {
  display: flex;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-right: 10px;
}

.title {
  background-color: silver;
  margin-bottom: 10px;
}

.text {
  flex: 1;
  background-color: cyan;
  min-height: 0;
  overflow: auto;
}

.photos {
  width: 100px;
  min-height: 0;
  overflow: auto;
}

.photos * ~ * {
  margin-top: 10px;
}

.thumbnail {
  background-color: lightgreen;
  aspect-ratio: 3;
}

HTML

<div class="card">
  <div class="photo">Photo</div>
  
  <div class="body">
    <div class="content">
      <div class="title">Title</div>
      <div class="text" contenteditable>
        Full text<br>
        Can be multiline and with vertical scroll
      </div>
    </div>
    
    <div class="photos">
      <div class="thumbnail">Thumbnail</div>
      <div class="thumbnail">Thumbnail</div>
      <div class="thumbnail">Thumbnail</div>
      <div class="thumbnail">Thumbnail</div>
    </div>
  </div>
</div>

解决方案

仅需调整.card和.body的Flexbox设置,就能让滚动区域正确工作:

修改后的CSS关键部分

.card {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 50%;
  min-width: 100px;
  max-width: 80%;
  max-height: 80%;
  border: solid 1px black;
  padding: 10px;
  /* 将卡片设为垂直方向的Flex容器 */
  display: flex;
  flex-direction: column;
  /* 确保容器能收缩,避免内容溢出 */
  min-height: 0;
}

.body {
  display: flex;
  /* 让body占据卡片剩余的全部高度 */
  flex: 1;
  /* 确保body内部元素能正确计算高度 */
  min-height: 0;
}

核心原理

  1. 将.card设为垂直Flex容器后,内部的.photo会按自身高度排列,.body则自动占据卡片剩余的可用高度,完美贴合卡片的max-height限制。
  2. 给.body设置flex:1和min-height:0,确保它不会超出卡片的高度范围,同时允许内部的Flex子元素(.content和.photos)正确计算可用空间。
  3. 原代码中.text和.photos的flex:1、min-height:0、overflow:auto设置已经正确,加上外层的Flex布局后,就能在内容超出时触发滚动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:15:42