CSS :nth-last-child() Pseudo-class

Definition and Usage

CSS :nth-last-child(n) The pseudo-class is used to match each element that is the nth child from the end of its parent element, regardless of its type.

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

Tip:View :nth-last-of-type() The pseudo-class is used to select each element that is the nth child from the end of its parent element, regardless of its type. n an element that is a child of another element.

Instance

Example 1

Specify the background color for each <p> element that is the second child from the end of its parent element:

p:nth-last-child(2) {
  background-color: red;
}

Try It Yourself

Example 2

odd and even Is a keyword that can be used to match child elements whose index is even or odd.

Here, we specify different background colors for all <p> elements whose last index is even or odd:

p:nth-last-child(odd) {
  background-color: red;
}
p:nth-last-child(even) {
  background-color: blue;
}

Try It Yourself

Example 3

Using the formula (an + bDescription: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 last index is a multiple of 3:

p:nth-last-child(3n+0) {
  background-color: red;
}

Try It Yourself

CSS Syntax

:nth-last-child(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 this pseudo-class.

Chrome Edge Firefox Safari Opera
4.0 9.0 3.5 3.2 9.6