CSS 伪类

CSS 伪类 :last-of-type  用于选择其父容器中该类型的最后一个元素并为其设置样式。这个伪类允许您将样式专门针对给定容器内最后一次出现的某种元素。

:last-child 与 :last-of-type

CSS 伪类选择器 :last-child 与 :last-of-type 类似,但有一个区别:它不太具体。 :last-child 只匹配父元素的最后一个子元素;而 :last-of-type 匹配指定元素的子元素,即使它不是最后一个。

语法

:last-of-type {
   /* ... */ 
} 

CSS :last-of-type 示例

这是一个 :last-of-type 伪类的示例,应用于 <p> 父元素下的 <p> 标记。

在此示例中,CSS 规则将仅应用于找到的最后一个 <p> 元素在 <div> 元素内,同一容器内的其他 <p> 元素不受影响。

<html>
<head>
<style>
   p:last-of-type {
      color: black;
      background: peachpuff;
      font-weight: 600;
      font-size: 1em;
      font-style: italic;
      padding: 5px;
   }
   div {
      border: 2px solid black;
      margin-bottom: 5px;
   }
</style>
</head>
<body>
           <div>父元素
       <p>第一个孩子,所以没有变化</p>
       <p>第二个孩子,所以没有变化</p>
       <p>最后一个子级,因此应用 :last-of-type 伪类</p>

   </div>
</body>
</html> 

以下是 :last-of-type 伪类的示例,应用于 <div> 和 <p> 元素。

在上面的示例中,last-of-type CSS 规则应用于 <div> 元素的最后一项,以及 <p> 元素。

<html>
<head>
<style>
   #container .item:last-of-type {
      color: blue;
      background-color: lightpink;
      font-weight: bold;
   }
   div,p {
      padding: 10px;
   }
</style>
</head>
<body>
   <div id="container">
           <div class="item">第一个 div,所以没有变化。</div>
       <div class="item">第二个 div,所以没有变化。</div>
       <div class="item">
          第三个 div,是父 div 的最后一个子元素,因此应用了 CSS。
       </div>
       <p class="item">其父级的最后一个 p 元素,由 .container.item 类选择器选择。</p>

   </div>
</body>
</html>