Categories
Tech Uncategorized

nth-child vs. nth-of-type

These are two CSS selectors which tend to confuse people quite a bit. A key difference is which elements are counted and how.

I found that it helps a lot to separate the children into two lists.

Let me explain!

Lets use this block of code to elaborate how these two selectors work:

:nth-of-type()

First, let’s start off looking at :nth-of-type(). It takes one argument, which is either a number or a formula to indicate the positions we are interested in.

Is it what you expected?

This is how I like to think of this selector in plain english. Split the children into two lists.

  1. Make a list of the p elements
  2. Of that list, we select the even numbered p elements

Note that, in this case this does NOT mean we select the 2nd, 4th, 6th etc. children of the div. We select the2nd, 4th, 6th etc. p elements relative to the other p elements. If we wanted to select the 2nd, 4th, 6th etc elements (i.e. the even elements) we would not specify an element type

:nth-child()

This selector is more straightforward.

To translate this selector into plain english as well (again using the above example):

  1. Make a list of the even elements
  2. Of that list, select the div elements

And that’s it! It’s really not as complicated as it looks, as long as you are clearly separating the children into two lists in your head:

  • One list of all the elements of the selected type within the container
  • One list of the specified numerical placement of these elements

And ensure that you are starting with the right list! 

Note: both of these selectors are CSS pseudo-classes which will match certain elements when they are in a specific state (in this case, the state refers to the numerical position the element occupies.)