A quote from the source below
Explaining the concept of using a formula (an + b): where a represents cycle size, n is a counter starting at 0, and b is an offset value.
An example is given to specify a background color for every third p
element:
p:nth-child(3n+0) { background: #ff0000; }
In summary, you can utilize the number :nth-child(n)
to target the nth child of an element.
You also have the option of using :nth-child(odd/even)
to select alternating children.
Lastly, you can apply the formula mentioned in the quote. By using 3n
, you can select every child with an index of 3
(the second child), while 5n
will target the child with an index of 5
(the fourth child), and so forth. Adding a value after the plus sign acts as an offset - selecting elements either before or after it.
For instance:
:nth-child(5n+2)
- This will choose every element two positions ahead of each 5th
element:
5 + 2
= Index of 7
, representing the 6th
element
10 + 2
= Index of 12
, representing the 11th
element
15 + 2
= Index of 17
, representing the 16th
element
20 + 2
= Index of 22
, representing the 21st
element
W3Schools - :nth-child()