选择 CSS 中的每 N 个元素

新手上路,请多包涵

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

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

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

有一个更好的方法吗?

原文由 Derek Adair 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 615
2 个回答

顾名思义, :nth-child() 允许您使用 n 变量以及常数来构造算术表达式。 You can perform addition ( + ), subtraction ( - ) and coefficient multiplication ( an where a is an integer, including positive numbers ,负数和零)。

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

 div:nth-child(4n)

有关这些算术表达式如何工作的解释,请参阅我对 这个问题 的回答以及 规范

请注意,此答案假定同一父元素中的所有子元素都具有相同的元素类型 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你只计算 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 选择器执行此操作。请参阅我对 这个问题 的回答。


顺便说一句,就 :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
...

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

原文由 BoltClock 发布,翻译遵循 CC BY-SA 3.0 许可协议

div:nth-child(4n+4)

请参阅: http ://css-tricks.com/how-nth-child-works/

原文由 Tomalak 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题