CSS 带有 mod(或 modulo)运算符的 nth-child
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6127814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
nth-child with mod (or modulo) operator
提问by jefflunt
Is it possible to use the nth-child
with modulo? I know you can specify a formula, such as
是否可以使用nth-child
with 模数?我知道你可以指定一个公式,比如
nth-child(4n+2)
But I can't seem to find if there's a modulo operator. I've tried the following examples below, and none seem to work:
但我似乎无法找到是否有模运算符。我已经尝试了以下示例,但似乎都不起作用:
nth-child(n%7)
nth-child(n % 7)
nth-child(n mod 7)
回答by Athlan
If you want to use nth-child
with modulo k
, just specify:
如果要nth-child
与 modulo一起使用k
,只需指定:
nth-child(kn)
For example, if you want to specify style for 3, 6, 9, ..elements, just specify (k
= 3), and use:
例如,如果要为3, 6, 9, ..元素指定样式,只需指定 ( k
=3),并使用:
nth-child(3n)
You can also specify an offset:
您还可以指定偏移量:
nth-child(kn+offset)
回答by BoltClock
No, :nth-child()
only supports addition, subtraction and coefficient multiplication.
不,:nth-child()
仅支持加法、减法和系数乘法。
I gather you're trying to pick up the first 6 elements (as n mod 7
for any positive integer n
only gives you 0
to 6
). For that, you can use this formula instead:
我猜你想拿起第6个要素(如n mod 7
对任意正整数n
只给你0
到6
)。为此,您可以改用此公式:
:nth-child(-n+6)
By negating n
, element counting is done backwards starting from zero, so these elements will be selected:
通过否定n
,元素计数从零开始向后进行,因此将选择这些元素:
0 + 6 = 6
-1 + 6 = 5
-2 + 6 = 4
-3 + 6 = 3
-4 + 6 = 2
-5 + 6 = 1
...
回答by Enethion
I know this topic is very old, but here's the answer that's close enought to modulo operator:
我知道这个话题很老了,但这里的答案与模运算符非常接近:
:not(:nth-child(7n))
This will select elements 1-6, 8-13 and so on...
这将选择元素 1-6、8-13 等等...
:nth-child(an)
The code above will select elements divisible by "a" so adding :not() selector forces CSS to select elements not divisible by "a".
上面的代码将选择可被“a”整除的元素,因此添加 :not() 选择器会强制 CSS 选择不能被“a”整除的元素。
I hope someone find it useful ;)
我希望有人觉得它有用;)
回答by Aaron Cicali
I know this topic is very old, but here's the answer:
我知道这个话题很老了,但这是答案:
.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;
}
This selector targets all children who are after the last child in the last full set of grouped children denoted by your nth-child formula.
此选择器针对在您的第 n 个孩子公式表示的最后一组完整分组孩子中的最后一个孩子之后的所有孩子。
回答by Maddocks
If you want modulous with n=2
than you can use even or odd.
如果你想要模数n=2
比你可以使用偶数或奇数。
tr:nth-child(even) {
background-color: #dddddd;
}