:first-child, :last-child, :nth-child, and :not(:nth-child)

By: Chris Goodwin
Multiple lockers against a wall

The :nth-child selector is both powerful and easy to use. It allows us to target specific elements based on their order in relation to each other. We can target something simple like the 4th child or something a bit more complex like every 5th child starting from the 2nd (2, 7, 12, 17,…). Once you know the basics you can write CSS that is powerful, fast, efficient, expandable, and smart.

Use of the :nth-child selector can often help to remove need for classes like .item--last or .item--clear. If you need to style in an iterative way, you can keep all styles contained in your CSS instead of adding extra classes to your HTML.

Best of all, the :nth-child selector was added in CSS3 and has support in all major browsers. This means we can use it without fear of browser support issues.

Here’s the structure of an :nth-child selector: an + b

  • (a) - An integer that provides context for the iteration of the (n)
  • (n) - Literally the letter ‘n’
  • (+/-) - Can be ‘+’ or ‘-’ to build the selector
  • (b) - An integer that provides context on the starting point

Here’s an example of a real world :nth-child selector: 3n - 2

  • a = 3
  • n = n
  • +/- = -
  • b = 2

Let’s have some fun!

By now you might already be thinking of some exciting things you can do with the :nth-child selector but if not, I’ve put together some examples. They start basic but become more complex.

:first-child

Allows us to target the first sibling in a group

:last-child

Allows us to target the last sibling in a group

:nth-child(3n)

Allows us to target every 3rd sibling in a group

:nth-child(n + 2)

Allows us to target every sibling in a group starting from the 2nd sibling

:nth-child(3n + 2)

Allows us to target every 3rd sibling in a group starting from the 2nd sibling

:nth-child(-n)

Allows us to target every sibling in a group starting from the 0th spot and working backwards (this doesn’t target any siblings as you can’t work backwards from the 0 place as there is no -1 sibling)

:nth-child(-n + 9)

Allows us to target every sibling in a group starting from the 9th spot and working backwards

:nth-child(-3n + 9)

Allows us to target every 3rd sibling in a group starting from the 9th spot and working backwards

:not(:nth-child(4n))

Allows us to target every sibling that is not the 4th sibling in a group

Using the :nth-child selector can take your CSS to the next level. It helps you write code that is organized, efficient, and expandable.

If you’re looking for more, you can read up on the spec, learn more from the MDN, or play around with your own recipes.