CSS :nth-of-type() Pseudo-class

Definition and Usage

CSS :nth-of-type(n) The pseudo-class is used to match the nth child element of the same type (tag name) as its parent element, n an element of each child element.

n can be a number/index, a keyword (odd or even) or a formula (such as an + b)

Tip:View :nth-child() The pseudo-class is used to select the nth child element as its parent element, where n is all non-negative integers starting from 0, n an element that is a child of another element, regardless of its type.

Instance

Example 1

How to use :nth-of-type() Selector:

/* Select the second element in the div sibling elements */
div:nth-of-type(2) {
  background: red;
}
/* Select the second li element in the list */
li:nth-of-type(2) {
  background: lightgreen;
}
/* Select every third element in any group of sibling elements */
:nth-of-type(3) {
  background: yellow;
}

Try it yourself

Example 2

odd and even Is a keyword that can be used to match child elements with odd or even indices (the index of the first child element is 1).

Here, we specify different background colors for <p> elements with odd and even indices:

p:nth-of-type(odd) {
  background: red;
}
p:nth-of-type(even) {
  background: blue;
}

Try it yourself

Example 3

Using the formula (an + b) Description:a Represents an integer step, n is all non-negative integers starting from 0,b Is an integer offset.

Here, we specify the background color for all <p> elements whose index is a multiple of 3 (to select the third, sixth, ninth, etc. elements):

p:nth-of-type(3n+0) {
  background: red;
}

Try it yourself

Example 4

Here, we specify the background color for all <p> elements whose index is a multiple of 3. Then we subtract 1 (to select the second, fifth, eighth, etc. elements):

p:nth-of-type(3n-1) {
  background: red;
}

Try it yourself

CSS syntax

:nth-of-type(index | odd | even | an+b) {
  css declarations;
}

Technical details

Version: CSS3

Browser support

The numbers in the table indicate the first browser version that fully supports the pseudo-class.

Chrome Edge Firefox Safari Opera
4.0 9.0 3.5 3.2 9.6