CSS - 伪类选择器 :last-of-type



CSS 伪类选择器:last-of-type用于选择并设置其父容器内最后一种类型元素的样式。此伪类允许您专门定位并应用样式到给定容器内最后出现的特定类型的元素。

:last-child vs :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>标签,在<div>父元素下。

在此示例中,CSS规则仅应用于在<div>元素中找到的最后一个<p>元素,而不会影响同一容器内的其他<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>Parent element
      <p>first child, so no change</p>
      <p>second child, so no change</p>
      <p>last child, so :last-of-type pseudo-class is applied</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">first div, so no change.</div>
      <div class="item">second div, so no change.</div>
      <div class="item">
         Third div, last child of the parent div, so CSS applied.
      </div>
      <p class="item">Last p element of its parent, selected by .container.item class selector.</p>
   </div>
</body>
</html>
广告
© . All rights reserved.