Reputation: 1572
I have nine sets of color schemes that I want to apply to a sequence of divs. Using :nth-child(1), :nth-child(2)...
works for the first nine, but I'd like the sequence to then repeat after that, and I can't wrap my head around the (3n+2) notation... I think I get it, but I can't seem to coax it into doing what I want.
Is this possible, or should I just apply a class to each div as I write them out?
Upvotes: 3
Views: 3454
Reputation: 723628
If you mean you need to apply different rules to every nine consecutive elements, you have to use these nine selectors:
:nth-child(9n+1)
:nth-child(9n+2)
:nth-child(9n+3)
:nth-child(9n+4)
:nth-child(9n+5)
:nth-child(9n+6)
:nth-child(9n+7)
:nth-child(9n+8)
:nth-child(9n+9) /* Or :nth-child(9n) */
Upvotes: 9
Reputation: 179046
First a few tidbits:
1
-based indices for matching (i.e. nth-child(1)
is the first child, not the second)n
in the An + B
notation is the iterator valuen
starts at 0
and counts upAn + B
will be a matched index (I'll call it i
)If you have a set of elements you want to match, you ought to write them out:
Example:
1st, 10th, 19th, 28th...
In this case you want to match n
to specific indices
n | i
======
0 | 1
1 | 10
2 | 19
3 | 28
4 | 37
etc...
If we solve for An + B = i
using n = 0
, i = 1
we can get the value of B:
A(0) + B = 1
B = 1
We can then use this value in a second substitution using n = 1
, i = 10
:
A(1) + 1 = 10;
A = 9;
So we now have 9n + 1
for a selector to match 1,10,19,28,etc
You can rinse and repeat for each different selection, but pretty soon you ought to realize that the repetition happens every A
elements, and the offset is B
elements.
The nth-child
selector is a great real-world example of where high-school algebra is actually useful
Upvotes: 6