【发布时间】:2011-03-28 14:22:08
【问题描述】:
是否可以选择一组元素中的每四个元素?
例如:我有 16 个 <div> 元素...我可以写类似的东西。
div:nth-child(4),
div:nth-child(8),
div:nth-child(12),
div:nth-child(16)
有没有更好的方法来做到这一点?
【问题讨论】:
标签: css css-selectors
是否可以选择一组元素中的每四个元素?
例如:我有 16 个 <div> 元素...我可以写类似的东西。
div:nth-child(4),
div:nth-child(8),
div:nth-child(12),
div:nth-child(16)
有没有更好的方法来做到这一点?
【问题讨论】:
标签: css css-selectors
顾名思义,:<b>n</b>th-child() 允许您使用n 变量和常数来构造算术表达式。您可以执行加法(+)、减法(-)和coefficient multiplication(an 其中a 是整数,包括正数、负数和零)。
以下是重写上述选择器列表的方法:
div:nth-child(4n)
有关这些算术表达式如何工作的说明,请参阅我对this question 的回答以及spec。
请注意,此答案假定同一父元素中的所有子元素都属于同一元素类型,div。如果您有任何其他不同类型的元素,例如h1 或p,则需要使用:nth-of-type() 而不是:nth-child(),以确保只计算div 元素:
<body>
<h1></h1>
<div>1</div> <div>2</div>
<div>3</div> <div>4</div>
<h2></h2>
<div>5</div> <div>6</div>
<div>7</div> <div>8</div>
<h2></h2>
<div>9</div> <div>10</div>
<div>11</div> <div>12</div>
<h2></h2>
<div>13</div> <div>14</div>
<div>15</div> <div>16</div>
</body>
对于其他所有内容(类、属性或这些的任意组合),如果您正在寻找与任意选择器匹配的第 n 个子项,您将无法使用纯 CSS 选择器执行此操作。请参阅我对this question 的回复。
顺便说一句,对于:nth-child(),4n 和 4n + 4 之间没有太大区别。如果你使用 n 变量,它从 0 开始计数。这是每个选择器将匹配的:
:nth-child(4n)
4(0) = 0
4(1) = 4
4(2) = 8
4(3) = 12
4(4) = 16
...
:nth-child(4n+4)
4(0) + 4 = 0 + 4 = 4
4(1) + 4 = 4 + 4 = 8
4(2) + 4 = 8 + 4 = 12
4(3) + 4 = 12 + 4 = 16
4(4) + 4 = 16 + 4 = 20
...
如您所见,两个选择器都将匹配上述相同的元素。在这种情况下,没有区别。
【讨论】:
tr td:nth-child(4)之类的东西。 注意括号内没有任何 n
div:nth-child(4n+4)
【讨论】:
试试这个
div:nth-child(4n+4)
【讨论】:
您需要nth-child 伪类的正确参数。
参数应采用an + b 的形式,以匹配从b 开始的每个ath 子。
a 和 b 都是可选整数,都可以为零或负数。
a 为零,则没有"every ath child" 子句。a 为负数,则从b 开始向后进行匹配。b 为零或负数,则可以使用正数b 编写等效表达式,例如4n+0 与 4n+4 相同。同样4n-1 与4n+3 相同。例子:
li:nth-child(4n) {
background: yellow;
}
<ol>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ol>
li:nth-child(4n+1) {
background: yellow;
}
<ol>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ol>
/* two selectors are required */
li:nth-child(4n+3),
li:nth-child(4n+4) {
background: yellow;
}
<ol>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ol>
/* when a is negative then matching is done backwards */
li:nth-child(-n+4) {
background: yellow;
}
<ol>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ol>
【讨论】: