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> 标签的 <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>