我有一个 HTML 表格,我想突出显示 3 行的交替组,这样第 0-3 行突出显示,第 4-6 行不突出显示,第 7-9 行突出显示,等等。
到目前为止我想出的最好的解决方案是:
tr:nth-child(6n + 1),
tr:nth-child(6n + 2),
tr:nth-child(6n + 3) {
background-color:#eee;
}
是否可以将这些选择器压缩成一个选择器?
最佳答案
是的,它可能在单个选择器中(但它是最好的吗???)
如果以 10 人为一组进行(如您的评论所说,这是您的最终目标),与拥有 10 个单独的选择器相比,这样做可能不值得,因为单独的选择器可能会更多清楚。
三人一组 ( see fiddle )
tr:not(:nth-child(6n+4)):not(:nth-child(6n+5)):not(:nth-child(6n+6)) {
background-color: #eee;
}
十人一组 ( see fiddle )
tr:not(:nth-child(20n+11)):not(:nth-child(20n+12)):not(:nth-child(20n+13)):not(:nth-child(20n+14)):not(:nth-child(20n+15)):not(:nth-child(20n+16)):not(:nth-child(20n+17)):not(:nth-child(20n+18)):not(:nth-child(20n+19)):not(:nth-child(20n+20)) {
background-color: #eee;
}
这显然不会消除您希望避免的代码复制/粘贴问题,并且对它是否符合“压缩”的条件存在疑问。但是,它被简化为单个选择器。
关于用于选择交替元素组的 CSS 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16239491/