CSS :last-of-type 伪类

CSS :last-of-type 伪类选择一个元素,该元素是其父元素的子元素列表中该类型的最后一个元素。

:last-of-type 伪类与 :nth-last-of-type 相同。

嵌套元素

也可以定位嵌套元素。

  • 选择器在没有编写简单选择器时被涉及。

目标嵌套元素示例:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      article:last-of-type {
        background-color: #8ebf42;
      }
    </style>
  </head>
  <body>
    <article>
      <div>This "div" is first.</div>
      <div>This <span>nested "span" is last</span>!</div>
      <div>This <em>nested "em" is first</em>, but this <em>nested "em" is last</em>!</div>
      This "b" qualifies!
      <div>This is the final "div"!</div>
    </article>
  </body>
</html>

:last-child 和 :last-of-type 选择器有相似之处,但它们之间有一个区别。

:last-child 非常具体,只匹配父元素的最后一个子元素,而 :last-of-type 匹配指定元素的最后一次出现。

CSS :last-of-type 和 :last-child 选择器示例:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p:last-of-type {
        background: #8ebf42;
        font-style: italic;
        color: #eee;
      }
      span {
        display: block;
      }
      span:last-child {
        background: #8ebf42;
        font-style: italic;
        font-weight: bold;
        color: #eee;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <h2>:last-of-type and :last-child selectors example</h2>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <span>Some text</span>
    <span>Some text</span>
    <span>Some text</span>
  </body>
</html>

语法

:last-of-type {
  css declarations;
}

:last-of-type 选择器的例子:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p:last-of-type {
        background: #8ebf42;
        font-style: italic;
        color: #eeeeee;
      }
    </style>
  </head>
  <body>
    <h2>:last-of-type selector example</h2>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
  </body>
</html>
日期:2020-06-02 22:14:36 来源:oir作者:oir