:last-of-type
试试看
语法
css
:last-of-type {
/* ... */
}
示例
设置最后一个段落的样式
HTML
html
<h2>Heading</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
CSS
css
p:last-of-type {
color: red;
font-style: italic;
}
结果
嵌套元素
此示例显示了如何定位嵌套元素。请注意,当没有写入简单选择器时,将隐式使用 通用选择器 (*
)。
HTML
html
<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>
<p>This `p` qualifies!</p>
<div>This is the final `div`!</div>
</article>
CSS
css
article :last-of-type {
background-color: pink;
}
结果
多个选择器元素
此 HTML 示例包含不同类型的嵌套元素。CSS 包含类型选择器和类选择器。
HTML
html
<p>This `p` is not selected.</p>
<p>This `p` is not selected either.</p>
<p>
This `p` is last `p` element of its parent e.g. `body` selected by `p` type
selector.
</p>
<div class="container">
<div class="item">This `div` is not selected.</div>
<div class="item">This `div` is not selected either.</div>
<div class="item">
This `div` is last `div` element of its parent `div` selected by `.container
.item` class selector.
</div>
<p class="item">
This `p` is last `p` element of its parent `div` selected by `.container
.item` class selector.
</p>
</div>
CSS
css
p:last-of-type {
background: skyblue;
}
.container .item:last-of-type {
color: red;
font-weight: bold;
}
结果
最后一个 <div>
和最后一个 <p>
都为红色和粗体,因为 .item:last-of-type
会选择每种类型中的最后一个,如果该最后一个元素也具有 item
类。
规范
规范 |
---|
选择器级别 4 # last-of-type-pseudo |
浏览器兼容性
BCD 表格仅在浏览器中加载