Course Recommendation:

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

Definition and Usage :nth-last-child(nCSS )

n Pseudo-classes are used to match each element that is the nth child from the end of its parent element, regardless of its type.odd Can be a number/index, a keyword ( evenor an+ b) or a formula (such as

Tip:View :nth-last-of-type() Pseudo-classes are used to select each element that is the nth child from the end of its parent element, regardless of its type. n of child elements.

Example

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 <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 specify the first browser version to fully support this pseudo-class.

Chrome Edge Firefox Safari Opera
4.0 9.0 3.5 3.2 9.6