Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Pseudo-classes

The :nth-of-type() pseudo-class

Reference for the CSS :nth-of-type() pseudo-class: match elements by position among siblings with the same tag name, using odd, even and an+b formulas.

The :nth-of-type() pseudo-class matches an element by its position among siblings that have the same tag name. Siblings with other tags are not counted at all, which makes it more predictable than :nth-child() when a container mixes different elements.

It accepts the same arguments: odd, even, a number, or an an+b formula. It does not support of S.

CSS
p:nth-of-type(2) {
  color: crimson;
}

Try it

Counting only paragraphs

In the first box the heading is ignored, so the second <p> is selected. In the second box, :nth-child(2) counts the heading as child 1, so the first paragraph is hit instead.

Syntax

CSS
:nth-of-type( <nth> ) { }

/* <nth> is one of: odd | even | <integer> | <an+b> */
  • Specificity: (0, 1, 0).
  • Type: the tag name (and namespace). Class names and attributes do not create separate types.

Values

Syntax and arguments Description
odd / even Odd or even positions among elements of that type.
3 The third element of its type.
2n Every second one: 2, 4, 6 ...
n + 2 The second and every one after it.
-n + 2 The first two.

Usage notes

  • Pair it with a type selector. img:nth-of-type(2) is clear. A bare :nth-of-type(2) matches the second element of every tag in the container, which is rarely intended.
  • Mixed containers. In an <article> with headings, paragraphs and figures, p:nth-of-type(odd) stripes only the paragraphs regardless of what sits between them.
  • Classes do not count. div.card:nth-of-type(2) means "the second <div> among siblings, and it must also have the class card". It does not mean "the second .card". For that, use :nth-child(2 of .card).
  • Document order, not visual order. Flexbox order, grid placement or flex-direction: row-reverse change what you see, not the counting.

Browser support

Supported in every browser.