CSS :last-child Pseudo Class

The CSS :last-child 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.

Originally the selected element had to have a parent. In Selectors Level 4, this is no longer required.

Version

Selectors Level 4

Selectors Level 3

Syntax

:last-child {
  css declarations;
}

Example of the :last-child selector:

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

Example of the last child of the <li> tag:

<!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>

Example of the last child of the <p> tag:

<!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>

Example of :last-child for HTML lists:

<!DOCTYPE html>
<html>
  <head>
    <style>
      ul li {
        color: #8ebf42;
      }
      ul li:last-child {
        border: 1px dotted #8ebf42;
        color: #1c87c9;
      }
    </style>
  </head>
  <body>
    <h2>:last-child selector example</h2>
    <ul>
      <li>List Item 1</li>
      <li>List Item 2</li>
      <li>
        List Item 3
        <ul>
          <li>List Item 3.1</li>
          <li>List Item 3.2</li>
          <li>List Item 3.3</li>
        </ul>
      </li>
    </ul>
  </body>
</html>

Browser support

chrome edge firefox safari opera
4.0+ 12.0+ 3.5+ 3.2+ 10.0+

Practice Your Knowledge

What does the :last-child CSS pseudo-class represent?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?