CSS :last-child 伪类

CSS :last-child 伪类选择元素,如果它是其他元素中的最后一个子元素。

:last-of-type 选择器可以用于如果用户想要选择并应用最后一个段落的样式,无论它是否是最后一个孩子。

最初选定的元素必须有一个父元素。
在 Selectors Level 4 中,这不再需要。

语法

:last-child {
  css declarations;
}

:last-child 选择器的例子:

<!DOCTYPE html>
<html>
  <head>
    <title>文档标题</title>
    <style>
      p:last-child {
        background-color: #1c87c9;
        color: #ffffff;
      }
    </style>
  </head>
  <body>
    <h2>Last-child selector 示例</h2>
    <p>把痛苦停在昨天 把微笑留给明天。</p>
    <p>把痛苦停在昨天 把微笑留给明天。</p>
  </body>
</html>

<li> 标签的最后一个孩子的例子:

<!DOCTYPE html>
<html>
  <head>
    <title>文档标题</title>
    <style>
      li:last-child {
        background: #1c87c9;
      }
    </style>
  </head>
  <body>
    <h2>:last-child 选择器示例</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>

<p> 标签的最后一个孩子的例子:

<!DOCTYPE html>
<html>
  <head>
    <title>文档标题</title>
    <style>
      p:last-child {
        background: #8ebf42;
      }
    </style>
  </head>
  <body>
    <h2>:last-child 选择器示例</h2>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <p>Paragraph 4</p>
  </body>
</html>

HTML 列表的 :last-child 示例:

<!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>
日期:2020-06-02 22:14:36 来源:oir作者:oir