选择 CSS 中的每 N 个元素 [英] Select every Nth element in CSS

查看:16
本文介绍了选择 CSS 中的每 N 个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以选择一组元素中的每四个元素?

Is it possible to select, say, every fourth element in a set of elements?

例如:我有 16 个 <div> 元素...我可以写类似的东西.

Ex: I have 16 <div> elements... I could write something like.

div:nth-child(4),
div:nth-child(8),
div:nth-child(12),
div:nth-child(16)

有没有更好的方法来做到这一点?

is there a better way to do this?

推荐答案

顾名思义,:nth-child() 允许你构造算术表达式除了常数之外,还使用 ​​n 变量.您可以执行加法 (+)、减法 (-) 和 系数乘法(an其中a为整数,包括正数、负数和零).

As the name implies, :nth-child() allows you to construct an arithmetic expression using the n variable in addition to constant numbers. You can perform addition (+), subtraction (-) and coefficient multiplication (an where a is an integer, including positive numbers, negative numbers and zero).

以下是重写上述选择器列表的方法:

Here's how you would rewrite the above selector list:

div:nth-child(4n)

有关这些算术表达式如何工作的说明,请参阅我对 这个问题,以及规范.

For an explanation on how these arithmetic expressions work, see my answer to this question, as well as the spec.

请注意,此答案假定同一父元素中的所有子元素都属于同一元素类型,div.如果您有任何其他不同类型的元素,例如 h1p,则需要改用 :nth-of-type():nth-child() 以确保您只计算 div 元素:

Note that this answer assumes that all of the child elements within the same parent element are of the same element type, div. If you have any other elements of different types such as h1 or p, you will need to use :nth-of-type() instead of :nth-child() to ensure you only count div elements:

<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 选择器执行此操作.查看我对这个问题的回答.

For everything else (classes, attributes, or any combination of these), where you're looking for the nth child that matches an arbitrary selector, you will not be able to do this with a pure CSS selector. See my answer to this question.

顺便说一句,在 :nth-child() 方面,4n 和 4n + 4 之间没有太大区别.如果你使用 n 变量,它从 0 开始计数.这是每个选择器将匹配的:

By the way, there's not much of a difference between 4n and 4n + 4 with regards to :nth-child(). If you use the n variable, it starts counting at 0. This is what each selector would match:

: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
...

如您所见,两个选择器都将匹配上述相同的元素.在这种情况下,没有区别.

As you can see, both selectors will match the same elements as above. In this case, there is no difference.

这篇关于选择 CSS 中的每 N 个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆