使用nth-child
和取模运算是否可行?我知道你可以指定一个公式,例如:
nth-child(4n+2)
但是我似乎找不到模运算符。我尝试了下面的示例,但没有一个有效:
nth-child(n%7)
nth-child(n % 7)
nth-child(n mod 7)
使用nth-child
和取模运算是否可行?我知道你可以指定一个公式,例如:
nth-child(4n+2)
但是我似乎找不到模运算符。我尝试了下面的示例,但没有一个有效:
nth-child(n%7)
nth-child(n % 7)
nth-child(n mod 7)
nth-child
并带有模数 k
,只需指定:nth-child(kn)
例如,如果您想为3、6、9...等元素指定样式,只需指定(k
= 3),并使用以下代码:nth-child(3n)
您还可以指定偏移量:
nth-child(kn+offset)
不,:nth-child()
只支持加法、减法和系数乘法。
我猜你想选择前6个元素(因为对于任何正整数n,n mod 7
仅给出0到6)。为了实现这一点,你可以使用以下公式:
:nth-child(-n+6)
通过取反 n
,元素计数将从零开始向后倒序进行,因此这些元素将被选中:
0 + 6 = 6
-1 + 6 = 5
-2 + 6 = 4
-3 + 6 = 3
-4 + 6 = 2
-5 + 6 = 1
...
n
。":nth-child(an+b)" 伪类符号表示文档树中在该元素之前有 "an" + "b"-1 个兄弟节点,其中 "n" 的值为任何正整数或零。它仅说明第一个子元素的索引为 1,与 n
的索引无关。 - BoltClock我知道这个话题很老,但是这里有一个足够接近取模运算符的答案:
:not(:nth-child(7n))
:nth-child(an)
n mod 7
匹配任何不被7整除的元素。这看起来更接近原始问题所询问的内容,尽管我们仍然需要从提问者那里得到确认。 - BoltClock我知道这个话题很老了,但是这里有答案:
.parent :nth-child(4n):nth-last-child(2) ~ *,
.parent :nth-child(4n):nth-last-child(3) ~ *,
.parent :nth-child(4n):nth-last-child(4) ~ * {
color: gold;
}
这个选择器针对的是在由nth-child公式表示的最后一个完整的分组子元素之后的所有子元素。
n=2
进行求模,则可以使用偶数或奇数。tr:nth-child(even) {
background-color: #dddddd;
}