这么说明不就一目了然,很多文档当中写得模糊不清,都不知具体有什么区别。
p:last-child 与 p:last-of-type 的核心区别
这两个 CSS 伪类最核心的区别:
p:last-child:必须是父元素的最后一个子元素,同时这个元素是<p>标签才生效p:last-of-type:只要求是父元素下所有<p>标签中的最后一个,不管它是不是父元素的最后一个子元素
1. 直观代码对比
我们用同一个 HTML 结构,分别测试两个选择器,一眼看懂区别:
<div class="parent">
<h2>标题</h2>
<p>第一段</p>
<p>第二段</p>
<span>其他标签</span>
</div>① p:last-child
/* 不生效!因为父元素最后一个子元素是 span,不是 p */
p:last-child {
color: red;
}生效条件:
- 是父元素的最后一个子元素
- 标签名必须是
<p>
② p:last-of-type
/* 生效!选中了最后一个 p 标签(第二段)*/
p:last-of-type {
color: blue;
}生效条件:
只需要是父元素里最后一个 <p>,不管后面有没有其他标签
2. 详细图解
父元素 div
├─ h2 (不是p,不影响)
├─ p (第一个p)
├─ p 【最后一个p】 → :last-of-type 选中它
└─ span(最后一个子元素,不是p) → :last-child 找不到任何p3. 什么时候用哪个?
| 选择器 | 用法场景 |
|---|---|
:last-child | 你确定最后一个子元素就是这个标签时使用 |
:last-of-type | 你只想选最后一个同类型标签,不管后面有没有其他元素 |