如何防止粘性表格表头横向滚动时内容侵入其他表头边框
如何防止粘性表格表头横向滚动时内容侵入其他表头边框
嗨,我来帮你搞定这个问题~你遇到的情况是因为表格设置了border-collapse: collapse,这种模式下所有单元格的边框会合并在一起,哪怕你的蓝色粘性表头z-index更高,它的白色边框位置其实和红色表头的边框是重叠的,滚动时红色表头就会透过这个缝隙露出来。
这里给你两个可行的解决办法:
方法一:改用border-collapse: separate并调整边框
把表格的边框合并模式改成分离,同时调整单元格的边框,避免出现双重边框:
.container { overflow: auto; width: 200px; } table { border-collapse: separate; /* 改成分离模式 */ border-spacing: 0; /* 去掉单元格间距 */ } th { background-color: red; border-right: 1px solid white; color: white; padding: 10px; } .sticky { background-color: blue; position: sticky; z-index: 2; } .test1 { left: 0; } .test2 { left: 57px; } .test3 { left: 114px; }
这种方式下,每个表头的边框都是独立的,粘性表头的白色边框会完全覆盖在红色表头的上方,滚动时就不会透出红色了。
方法二:给粘性表头添加伪元素覆盖边框区域
如果不想改动表格的border-collapse属性,可以给粘性表头加一个右侧的白色伪元素,把可能透出红色的区域盖住:
.container { overflow: auto; width: 200px; } table { border-collapse: collapse; } th { background-color: red; border-right: 1px solid white; color: white; padding: 10px; position: relative; /* 让伪元素可以定位 */ } .sticky { background-color: blue; position: sticky; z-index: 2; } /* 添加伪元素盖住右侧边框位置 */ .sticky::after { content: ''; position: absolute; top: 0; right: 0; width: 1px; height: 100%; background-color: white; z-index: 3; /* 确保在最上层 */ } .test1 { left: 0; } .test2 { left: 57px; } .test3 { left: 114px; }
这个伪元素会在粘性表头的右侧生成一个白色的竖条,刚好覆盖边框位置,滚动时就能挡住下面的红色表头了。
你可以根据自己的需求选其中一种方法试试,亲测有效哦~
备注:内容来源于stack exchange,提问作者epatmalnieks
相关产品推荐
相关产品推荐

