用于选择交替元素组的 CSS 选择器

标签 css css-selectors

我有一个 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/

相关文章:

html - 当属性为 'width' 时,属性选择器不适用于表

html - 最后应用了哪一个?

html - 当不透明度为零时,如何隐藏 HTML 文本输入中的插入符号? (IE)

html - 将 div 直接放在父 div 之上

java - Vaadin 中的着色表

html - 单击显示/隐藏仅 div 的 css 且没有 href。没有jquery

css - 位置绝对和底部 0

css - 为什么直接定义CSS类不适用?

javascript - 使用 :not(:not()) to emulate (the hypothetical) :is() selector in jQuery

python - 使用 python 进行网页抓取 - 较旧的 html 设计。 .数据表