last-of-type

CSS :last-of-type Pseudo Class

The CSS :last-of-type pseudo-class selects an element that is the last element of its type in the list of children of its parent.

The :last-of-type pseudo-class is the same as the :nth-last-of-type.

Version

Version

CSS2 Universal Selector

CSS2 Universal Selector

Syntax

Syntax

:last-of-type {
  css declarations;
}

Example of the :last-of-type selector:

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

Nested elements

Nested elements

Nested elements can also be targeted.

The * selector is involved when no simple selector is written.

Example of targeted nested elements:

<!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>
      <b>This "b" qualifies!</b>
      <div>This is the final "div"!</div>
    </article>
  </body>
</html>

The :last-child and the :last-of-type selectors have similarities but there is one difference between them. The :last-child is very specific and only matches the very last child of the parent element, whereas the :last-of-type matches the last occurrence of the specified element.

Example of CSS :last-of-type and :last-child selectors:

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


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

扫一扫,反馈当前页面

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