CSS :nth-last-child() Selector

CSS :nth-last-child(n) selector selects every element that is the nth last child of its parent, regardless of the type of the parent element.

Here n can be a:

  • Number – Like 1, 2, 3, 4, …..
  • Keyword – Like odd and even
  • Formula – Like 2n+1, 3n+1, etc.

For example, if you set n=2, it would select every 2nd element counting from the last within its parent. Similarly, if you set n=3, it would select every 3rd element counting from the last within its parent.

In the following example, the :nth-last-child(3) selector selects every 3rd element counting from the last within its parent(regardless of its type) and sets a yellow background color to it:

Example:

:nth-last-child(3){
   background: yellow;
}

To make things simple, CSS has introduced keywords like odd & even that we can directly use to select elements that are at odd and even positions counting from the last.

In the following example, the :nth-last-child() selector will set a yellow background to all <p> elements which are at the odd positions and a cyan color background to those <p> elements which are at the even positions within their parent counting from the last.

Example:

p:nth-last-child(odd){
   background: yellow;
}
p:nth-last-child(even){
   background: cyan;
}

The :nth-last-child() selector can also select elements that satisfy a particular formula in the form of (an+b). Here, a & b can be any numbers.

For example, (2n+1) will select all the elements that are at the odd(1, 3, 5, ….) positions and (2n+0) will select all the elements that are at the even(2, 4, 6, ….) positions within their parent but counting from the last.

Here is a working example:

Example:

p:nth-last-child(2n+1){
   background: yellow;
}
p:nth-last-child(2n+0){
   background: cyan;
}

CSS Syntax

The syntax of the :nth-last-child() selector is as follows:

:nth-last-child(n){
    CSS Styles;
}

Browser Support

The number in each cell of the table specifies the first version of the browser that fully supports the :nth-last-child() selector.

Selector
:nth-last-child()4.09.03.53.29.6

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.