
本文介绍一种基于 CSS Grid 的纯 CSS 方案,无需 JavaScript 或 div 模拟,即可实现语义化 中 thead 和 tfoot 固定定位、tbody 独立垂直滚动且滚动条仅出现在 tbody 区域的效果。
本文介绍一种基于 css grid 的纯 css 方案,无需 javascript 或 div 模拟,即可实现语义化 `
table {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 根据实际列数调整 */
grid-template-rows: 1fr fit-content(128px) 1fr; /* 关键:thead/tfoot 自适应,tbody 高度受限 */
width: 100%;
border-collapse: collapse;
}
/* 所有表格部分均转为子网格,继承列轨道 */
thead, tbody, tfoot, tr {
display: grid;
grid-template-columns: subgrid;
grid-column: 1 / -1; /* 跨所有列,兼容任意列数 */
}
th, td {
border: 1px solid #000;
padding: 8px 12px;
text-align: left;
}
/* tbody 单独启用滚动,不设 height/max-height —— 由 grid-template-rows 控制 */
tbody {
overflow-y: auto;
overflow-x: hidden;
}
/* tfoot 固定在容器底部(相对于 grid 容器)*/
tfoot {
position: sticky;
bottom: 0;
background-color: #fff;
z-index: 1;
}
/* thead 固定在顶部 */
thead {
position: sticky;
top: 0;
background-color: #fff;
z-index: 2;
}
| 姓名 | 邮箱 | 状态 |
|---|---|---|
| 张三 | zhang@example.com | 激活 |
| 李四 | li@example.com | 禁用 |
| 共 12 条记录 | ||
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











