table高度为100%时如何设置<tr>固定高度且tfoot置底
问题根因
原生表格的默认布局算法存在固定逻辑:当<table>设置了height: 100%这类确定高度时,浏览器会先累加所有子行(表头行、数据行、表脚行)的声明高度,如果总和小于表格自身高度,会把剩余空间平均分配给所有行,直接覆盖你给<tr>设置的固定高度值,这就是设置height:49px不生效的核心原因。
如果直接去掉table的100%高度,表格高度完全由内容撑开,内容不足时tfoot自然会跟着内容上移,无法贴住父容器底部。
实现方案
不需要额外嵌套DOM结构,仅需调整CSS、补全规范的表格结构即可满足需求,兼容所有主流浏览器:
- 保留table的
height: 100%、table-layout: fixed配置,保证表格撑满父容器、列宽稳定不随内容波动 - 给所有业务行(表头行、数据行、表脚行)保留
height: 49px的固定高度设置 - 给
<tbody>添加一个display: table-row的伪元素作为填充行,这个行不设置固定高度,会自动吃掉表格所有剩余空白空间,避免浏览器拉伸业务数据行 - 补全表格规范结构:
<thead>和<tfoot>内的单元格必须包裹在<tr>标签内,避免浏览器自动补全节点导致的样式异常
修正后完整代码
CSS部分
html, body { height: 100%; width: 100%; margin: 0; padding: 0; } .parent { width: 100%; height: 100%; } table { width: 100%; height: 100%; table-layout: fixed; border-spacing: 0px; border-collapse: collapse; } thead tr { height: 49px; background: lightblue; position: sticky; top: 0; } thead th { height: 49px; background: lightblue; border-bottom: 1px solid #000; } tbody tr { height: 49px; } tbody td { height: 49px; border-bottom: 1px solid #000; } /* 填充剩余空间的伪行 */ tbody::after { content: ""; display: table-row; height: auto; } tfoot tr { height: 49px; background: lightblue; } tfoot td { height: 49px; position: sticky; bottom: 0; background: lightblue; border-top: 1px solid #000; }
HTML部分
<div class="parent"> <table> <thead> <tr> <th>Col 1</th> <th>Col 2</th> <th>Col 3</th> <th>Col 4</th> <th>Col 5</th> </tr> </thead> <tbody> <tr> <td>Row 1 Col 1</td> <td>Row 1 Col 2</td> <td>Row 1 Col 3</td> <td>Row 1 Col 4</td> <td>Row 1 Col 5</td> </tr> <tr> <td>Row 2 Col 1</td> <td>Row 2 Col 2</td> <td>Row 2 Col 3</td> <td>Row 2 Col 4</td> <td>Row 2 Col 5</td> </tr> <tr> <td>Row 3 Col 1</td> <td>Row 3 Col 2</td> <td>Row 3 Col 3</td> <td>Row 3 Col 4</td> <td>Row 3 Col 5</td> </tr> </tbody> <tfoot> <tr> <td colspan="5">I am the footer deal with it</td> </tr> </tfoot> </table> </div>
效果说明
- 所有数据行、表头、表脚高度严格保持49px,不会被自动拉伸
- 当数据行总高度不足时,tbody内的伪填充行自动占满剩余空白,tfoot始终贴在父容器底部
- 当数据行过多超出容器高度时,配合sticky定位的表头表脚可正常固定,内容区域滚动
内容的提问来源于stack exchange,提问作者Craig Howell
相关产品推荐
相关产品推荐

