X

Headline

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

CSS :last-child Pseudo Class

The :last-child CSS pseudo-class selects the element if it is the last child among the other elements.

The :last-of-type selector can be used if the user wants to select and apply the style on the last paragraph whether or not it is the last child.

Version

CSS3

Syntax

:last-child {
css declarations;
}

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p:last-child {
      background-color: #1c87c9;
      color:#fff;
      }
    </style>
  </head>
  <body>
    <h2>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 :last-child selector:

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      li:last-child {
      background: #1c87c9;
      } 
    </style>
  </head>
  <body>
    <h2>:last-child selector example</h2>
    <ul>
      <li>Paris</li>
      <li>Moscow</li>
      <li>Rome</li>
    </ul>
    <ol>
      <li>Paris</li>
      <li>Moscow</li>
      <li>Rome</li>
    </ol>
  </body>
</html>

In this example the p:last-child selector selects the last paragraph:

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style> 
      p:last-child {
      background: #8ebf42;
      }
    </style>
  </head>
  <body>
    <h2>:last-child selector example</h2>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <p>Paragraph 4</p>
  </body>
</html>

Browser support

4.0+ 12.0+ 3.5+ 3.2+ 10.0+

Practice Your Knowledge

The :last-child CSS pseudo-class selects the element



Do you find this helpful?

Related articles