last-child

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

Version

Selectors Level 4

Selectors Level 3

Syntax

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>


请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部