如何使用NG ZORRO实现表格滚动时表头(thead)固定在顶部?
NG ZORRO表格表头固定解决方案
当使用NG ZORRO表格尝试通过position: sticky固定表头无效时,核心问题在于缺少滚动容器以及样式未作用到正确的DOM元素,以下是可行的解决步骤:
问题分析
- 默认情况下,nz-table会自适应内容高度,没有生成滚动容器,
sticky定位需要父容器存在overflow-y: auto/scroll才能生效。 - NG ZORRO表格会生成嵌套的DOM结构(如
.nz-table-inner-wrap、.ant-table-thead),直接给原生thead设置样式无法覆盖组件自带的样式,也无法作用到正确的元素上。
解决方案代码
修改后的CSS
.table-fixed .nz-table-inner-wrap { max-height: 400px; /* 根据需求设置表格的最大高度 */ overflow-y: auto; } .table-fixed .ant-table-thead > tr > th { position: sticky !important; top: 0; /* 如果页面有顶部导航栏,可设置为导航栏高度,如top: 60px */ z-index: 10; background-color: #000; color: #fff; }
保留原HTML结构
template: ` <nz-table #colSpanTable [nzData]="listOfData" nzBordered class='table-fixed'> <thead> <tr> <th>Name</th> <th>Age</th> <th colspan="2">Home phone</th> <th>Address</th> </tr> </thead> <tbody> <tr *ngFor="let data of colSpanTable.data; index as i"> <td>{{ data.name }}</td> <td>{{ data.age }}</td> <td>{{ data.phone1 }}</td> <td>{{ data.phone2 }}</td> <td>{{ data.address }}</td> </tr> </tbody> </nz-table> `
关键说明
- 给
.nz-table-inner-wrap设置max-height和overflow-y: auto,让表格内容在超出高度时产生滚动,为sticky定位提供滚动上下文。 - 针对NG ZORRO生成的
.ant-table-thead > tr > th设置sticky,确保样式能正确作用到表头单元格,z-index用于保证表头在滚动时不会被内容遮挡。
内容的提问来源于stack exchange,提问作者Ngọc Trần
相关产品推荐
相关产品推荐

