X

Headline

This is an important message requiring you to make a choice if you're based in the EU.

CSS :nth-last-child Pseudo Class

The :nth-last-child() pseudo-class selects elements based on their index starting from the last element upwards.

The :nth-last-child() can be specified by a number, a keyword, or a formula.

Version

CSS3

Syntax

:nth-last-child() {
css declarations;
}

Let's see the example.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p:last-child {
      background-color: #1c87c9;
      color:#fff;
      }
    </style>
  </head>
  <body>
    <h2>:nth-last-child selector example</h2>
    <p>Lorem ipsum is simply dummy text...</p>
    <p>Lorem Ipsum is simply dummy text...</p>
  </body>
</html>

Another example with the :nth-last-child() selector:

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style> 
      p:nth-last-child(odd) {
      background: #1c87c9;
      color:#eee;
      }
      p:nth-last-child(even) {
      background: #666;
      color:#eee;
      }
    </style>
  </head>
  <body>
    <h2>:nth-last-child selector example</h2>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
  </body>
</html>


Browser support

4.0+ 12.0+ 3.5+ 3.2+ 10.0+

Practice Your Knowledge

The :nth-last-child() pseudo-class selects elements



Do you find this helpful?

Related articles