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

如何实现tbody垂直滚动并自动填充父容器剩余空间?

解决方案:让表格填充父容器剩余垂直空间并实现tbody滚动

问题说明

需要让三个卡片内的表格自动填充卡片的剩余垂直空间,且表格tbody区域可垂直滚动,此前尝试多种方案未生效。

修改步骤及代码实现

  1. 调整卡片容器布局
    给每个卡片容器设置垂直方向的flex布局,确保内部元素能按垂直方向分配空间:
.container div {
  width: 250px;
  display: flex;
  flex-direction: column;
  height: 100%;
}
  1. 配置表格实现滚动与空间填充
    通过flex布局让表格占满剩余空间,同时单独设置tbody的滚动属性,保证表头固定、内容可滚动:
table {
  width: 100%;
  text-align: center;
  border-collapse: collapse;
  flex: 1; /* 让表格占据卡片剩余垂直空间 */
  display: flex;
  flex-direction: column;
}

thead {
  flex-shrink: 0; /* 固定表头,不随内容收缩 */
}

tbody {
  flex: 1;
  overflow-y: auto; /* 开启垂直滚动 */
  display: block;
}

/* 保证表头与内容列宽对齐,避免错位 */
thead tr, tbody tr {
  display: table;
  width: 100%;
  table-layout: fixed;
}

完整CSS代码

html {
  background: black;
}

.container {
  display: flex;
  height: 200px;
  background: rgb(0, 50, 0);
  padding: 10px;
  color: white;
  justify-content: space-between
}

.container div {
  width: 250px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.ex-1 {
  background-color: rgb(0, 100, 100);
}

.ex-2 {
  background-color: rgb(100, 0, 100);
}

.ex-3 {
  background-color: rgb(0, 0, 100);
}

table {
  width: 100%;
  text-align: center;
  border-collapse: collapse;
  flex: 1;
  display: flex;
  flex-direction: column;
}

thead {
  flex-shrink: 0;
}

tbody {
  flex: 1;
  overflow-y: auto;
  display: block;
}

thead tr, tbody tr {
  display: table;
  width: 100%;
  table-layout: fixed;
}

关键原理

  • 卡片容器使用垂直flex布局,让表格能够自动填充剩余高度;
  • 将table转为flex容器,thead固定高度,tbody占据剩余空间并开启垂直滚动;
  • 通过table-layout: fixed保证表头和内容的列宽一致,避免错位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:42:26