Go back to home page of Unsolicited Advice from Tiffany B. Brown

How :nth-of-type() works … a redux

In my post How the :nth-child() and :nth-of-type() pseudo-classes work, I tried to demystify how the :nth-of-type pseudo-class works. Although I didn't get it wrong, I didn't get it quite right either.

First a recap: in the previous post, I used the SVG document below to illustrate how :nth-of-type() works.

I also wrote:

To select the second star, you might think that we'd use .star:nth-of-type(2). But as you can see in Figure 10, that doesn't work. Using .star:nth-of-type(2) is like saying match the second child if its class name is star, and not match the second star.

And that is absolutely true and correct. However, here's the behavior of nth-of-type() as defined by the Selectors Level 3 specification:

The :nth-of-type(an+b) pseudo-class notation represents an element that has an+b-1 siblings with the same expanded element name before it in the document tree, for any zero or positive integer value of n, and has a parent element.

In other words, :nth-of-type() is inteded for use with elements. It behaves differently when used with other types of selectors. In the example above, and all of the examples used in the previous post, I used polygon elements with two different class names: hex and star.

A clearer example — one that's in line with the intended behavior of :nth-of-type() — would have used different elements, such as the image below.

Here we have ten shape elements. Five of these are circle elements. Five are rect elements. Here's what happens when we use circle:nth-of-type(2).

Our selector matches the second circle element, as we'd expect.

Get CSS Master

Did you learn something from this blog post? You might like the latest edition of CSS Master. It contains several nuggets of CSS joy like this one. Buy now from SitePoint