Chrome浏览器中Angular mat-table双粘性表头出现异常间距问题
问题根因
这个问题是Chrome浏览器和Firefox对sticky定位表格元素的渲染逻辑差异导致的:
- Chrome对sticky定位的表格行会产生亚像素级的偏移,生成肉眼可见的间隙,且border-collapse属性对脱离普通文档流的sticky元素不生效,所以你之前设置的border-collapse没有作用
- 透字问题是因为sticky表头没有显式设置堆叠层级,下方滚动的内容堆叠层级高于表头,导致文字透出
解决方案
你可以按照以下步骤修改代码即可解决:
1. 替换表格相关CSS
将你原有的表格样式替换为以下内容:
.example-container { height: 400px; overflow: auto; } .mat-table-sticky { background: #59abfd; opacity: 1; /* 提升堆叠层级解决透字 */ z-index: 10 !important; background-clip: padding-box !important; } .mat-table { background-color: red; /* 用border-spacing代替border-collapse更适配Chrome下的sticky表格 */ border-spacing: 0 !important; border-collapse: unset !important; } .example-sticky-toggle-group { margin: 8px; } .mat-column-filler { padding: 0 8px; font-size: 10px; text-align: center; } .mat-header-cell, .mat-footer-cell, .mat-cell { min-width: 80px; box-sizing: border-box; /* 移除默认边框间隙 */ border: none !important; margin: 0 !important; } /* 固定行高避免Chrome亚像素计算偏差产生间隙 */ .mat-header-row, .mat-footer-row, .mat-row { min-width: 1920px; /* 24 columns, 80px each */ height: 56px !important; margin: 0 !important; border: none !important; } /* 用内阴影覆盖两行表头之间的间隙 */ .mat-header-row:nth-of-type(2).mat-table-sticky { box-shadow: 0 -1px 0 #59abfd inset !important; } .mat-table-sticky-border-elem-top { border-bottom: 2px solid midnightblue; } .mat-table-sticky-border-elem-right { border-left: 2px solid midnightblue; } .mat-table-sticky-border-elem-bottom { border-top: 2px solid midnightblue; } .mat-table-sticky-border-elem-left { border-right: 2px solid midnightblue; }
2. 处理样式封装问题
如果以上样式放在组件的css文件中不生效,是因为Angular的样式封装隔离了组件内样式对mat-table内部元素的作用,你可以选择以下任意一种方式解决:
- 将以上样式添加到项目全局的
styles.css/styles.scss文件中 - 在组件样式中使用::ng-deep穿透,例如
::ng-deep .mat-table-sticky {/* 样式内容 */} - 给组件添加
encapsulation: ViewEncapsulation.None配置(需要注意组件内样式会污染全局样式,建议给表格加专属类名限定范围)
修改完成后即可同时解决Chrome下的表头间隙和透字问题,不会影响Firefox下的原有表现。
内容的提问来源于stack exchange,提问作者Hasan Gilani
相关产品推荐
相关产品推荐

