ComparisonComparisons

:nth-child() vs :nth-of-type()

nth-child() counts every one of the parent’s elements, regardless of tag. nth-of-type() only counts siblings that share the same tag as the chosen selector.

On this page

Side-by-side comparison

#

Example

#
CSS
p:first-child { background: #7c3aed; color: #fff; }
Preview

Nothing gets highlighted: the article’s first child is the h4, not a paragraph.

Definition and usage

#

The :nth-child() pseudo-class numbers every child of the parent, starting at 1, regardless of what tag they are. It accepts a specific number, the words odd and even, or an An+B pattern, exactly like its sibling pseudo-class.

:nth-of-type() uses the same argument syntax, but only counts siblings that share the same tag as the element on the left side of the selector. In a parent where paragraphs alternate with images, p:nth-of-type(2) points to the second paragraph, even if other elements come before it.

A classic trap is p:first-child, which matches nothing if a heading comes before the first paragraph, because the heading is the parent’s actual first child. p:first-of-type solves that. On the other hand, only :nth-child() understands the newer of <selector> syntax, which counts by class rather than by tag.

Syntax

#
Syntax
:nth-child( <number> | odd | even | An+B [of <selector>]? )
:nth-of-type( <number> | odd | even | An+B )

More examples

#
nth-of-type fixes this trap
CSS
p:first-of-type { background: #7c3aed; color: #fff; }
Preview

Now the first paragraph gets highlighted, even though it comes after the heading in the markup.

A different result in a list with mixed tags
CSS
span:nth-of-type(even) { background: #7c3aed; color: #fff; }
Preview

nth-of-type only counts among the span elements (2 and 4), ignoring the em elements sitting between them. nth-child(even) would count completely different elements.

Good practices

#
  • When different tags mix inside a parent, :nth-of-type() usually gives a more predictable result than :nth-child().
  • Only :nth-child() understands the "of selector" syntax, e.g. :nth-child(2 of .hot), which counts by class.
  • Classic trap: p:first-child won’t work if a heading comes before the first paragraph. Use p:first-of-type.

Related entries

#

Spotted a mistake or missing an example? Write to us.