开发者

nth-Child CSS selectors

开发者 https://www.devze.com 2023-03-30 20:09 出处:网络
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 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 sh开发者_如何学Could I just apply a class to each div as I write them out?


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) */


First a few tidbits:

  • nth-child uses 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 value
  • n starts at 0 and counts up
  • An + B will be a matched index (I'll call it i)

read the spec for more info

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号