CSS selectors Nth-Child

I have nine sets of color schemes that I want to apply to a sequence of divs. Usage :nth-child(1), :nth-child(2)...works for the first nine, but after that I would like the sequence to repeat after that, and I can’t wrap my head around the (3n + 2) notation ... I think I understand, but I cannot seem to have it coax it, doing what I want. Is this possible, or should I just apply a class to each div when I write them out?

Thanks!

+3
source share
2 answers

If you mean that you need to apply different rules for every nine consecutive elements, you should 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) */
+8
source

First, a few tidbits:

  • nth-child uses based indexes 1for matching (i.e. nth-child(1), this is the first child, not the second)
  • nthe designation An + Bindicates the value of the iterator
  • nstarts with 0and counts
  • An + Bwill be a matching index (I will call it i)

read the specification for more information

If you have a set of elements that you want to map, you should write them:

Example:

1st, 10th, 19th, 28th...

In this case, you want to map nto specific indices

n | i
======
0 |  1
1 | 10
2 | 19
3 | 28
4 | 37
etc...

An + B = i n = 0, i = 1, B:

A(0) + B = 1
B = 1

, n = 1, i = 10:

A(1) + 1 = 10;
A = 9;

, 9n + 1 , 1,10,19,28,etc

, , A, - B.

nth-child - ,

+5

All Articles