Repeating patterns with :nth-child

Example #1

Repeating 3-item pattern...

div:nth-child(3n+1){ background: #FF7100; } div:nth-child(3n+2){ background: #FFB173; } div:nth-child(3n+3){ background: #A64A00; }

The equation passed into nth-child above is basically (an+b), where n={0,1,2,3...} (that is, n is a set of all positive integers).

So when we substitute in all the values of n then the first selector above evaluates to nth-child(3*0+1) or nth-child(1), then nth-child(3*1+1) or nth-child(4), then nth-child(3*2+1) or nth-child(7) and so on.

The second selector evaluates to nth-child(3*0+2) or nth-child(2), then nth-child(3*1+2) or nth-child(5), then nth-child(3*2+2) or nth-child(8) and so on.

And following the same pattern the 3rd selector results in nth-child(3), nth-child(6), nth-child(9), and so on.

Below are a couple more examples.


Example #2

Repeating 4-item pattern...

div:nth-child(4n+1){ background: #ccc; } div:nth-child(4n+2){ background: #999; } div:nth-child(4n+3){ background: #666; } div:nth-child(4n+4){ background: #333; }

Example #3

Repeating 7-item pattern...

.ex3 div:nth-child(7n+1){ background: red; } .ex3 div:nth-child(7n+2){ background: orange; } .ex3 div:nth-child(7n+3){ background: yellow; } .ex3 div:nth-child(7n+4){ background: green; } .ex3 div:nth-child(7n+5){ background: blue; } .ex3 div:nth-child(7n+6){ background: indigo; } .ex3 div:nth-child(7n+7){ background: violet; }

MDN says:

The :nth-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings before it in the document tree, for a given positive or zero value for n, and has a parent element.

This can more clearly be described this way: the matching element is the bth child of an element after all its children have been split into groups of a elements each.

The values a and b must both be integers, and the index of an element's first child is 1.

In other words, this class matches all children whose index fall in the set { an + b; n = 0, 1, 2, ... }.

nth-child, Mozilla Developer Network

Also more at CSS-Tricks: There is a CSS selector, really a pseudo-selector, called nth-child.