Screen Shot 2013-09-29 at 1.56.12 PM

Repeating patterns in CSS with :nth-child and :nth-of-type

“What we call chaos is just patterns we haven’t recognized. What we call random is just patterns we can’t decipher.” ― Chuck Palahniuk

I’ve been trying to wrap my head around how the :nth-child pseudo-class can be used to create repeating patterns with CSS, beyond just even and odd (which are perfect for zebra-striping table rows, amongst other things). What really helped me understanding it was coding up a few examples to play around with. These examples are all available on CodePen too, so you can fork or edit them there if you want. I’ll embed the pen at the bottom. Note that while I will use :nth-child for all of the examples below, they should all work just as well with the :nth-of-type pseudo-class.

Example #1

Repeating 3-item pattern…

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…

Example #3

Repeating 7-item pattern…

Learn more about :nth-child

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.

UPDATE: Another must-see resource: Master of the :nth-child

CodePen Style

Check out this Pen!

2 thoughts on “Repeating patterns in CSS with :nth-child and :nth-of-type

Leave a Reply

Your email address will not be published. Required fields are marked *