使用 :first-of-type 伪类可以选中父元素中指定标签名的第一个子元素。它基于元素的标签名(如 p、div)进行匹配,而非类名或 id。例如,在包含多个 p 标签的容器中,p:first-of-type 只会影响第一个 p,忽略后续的 p 或其他类型的元素。

:first-of-type 与 :first-child 的区别是什么?
:first-of-type 匹配同类型标签的第一个,而 :first-child 必须同时是父元素的第一个子节点且标签匹配。如果第一个子节点不是目标标签,:first-child 将失效,但 :first-of-type 仍能选中后续的同标签首个元素。

<!DOCTYPE html>
<html>
<head>
<style>
/* 选中第一个 p,无论它前面是否有其他标签 */
p:first-of-type {
color: red;
}
/* 仅当 p 是父元素第一个子节点时才生效 */
p:first-child {
font-weight: bold;
}
</style>
</head>
<body>
<div>
<span>Span First</span>
<p>Para 1 (Red, Not Bold)</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill13837" title="htmlq 命令行 HTML 内容提取器,支持 CSS 选择器"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20d3191a227.jpg" alt="htmlq 命令行 HTML 内容提取器,支持 CSS 选择器" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill13837" title="htmlq 命令行 HTML 内容提取器,支持 CSS 选择器">htmlq 命令行 HTML 内容提取器,支持 CSS 选择器</a>
<p>htmlq 是一个命令行工具,使用 CSS 选择器从 HTML 中提取内容,相当于 jq 的 HTML 版本。该工具使用 Rust 编写,允许你通过 CSS 选择器将 HTML 管道化,直接从终端提取文本、属性和结构化内容。</p>
</div>
<a href="/xiazai/skill13837" title="htmlq 命令行 HTML 内容提取器,支持 CSS 选择器" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p>
<p>Para 2 (Normal)</p>
</div>
</body>
</html>当混合不同标签时 :first-of-type 的行为如何?
在混合标签结构中,:first-of-type 仅关注特定标签名的顺序。例如,若父元素中有 div、p、span、p,则 p:first-of-type 选中第二个子元素(第一个 p),而 span:first-of-type 选中第三个子元素。它不关心其他类型的存在,只按标签名分组并取每组的首个。

















