:first-of-type 选择同类型子元素中的首个元素,如 p:first-of-type 匹配首个 p 标签,不一定是父元素的第一个子节点,与 :first-child 不同,后者要求必须是第一个子元素。

:first-of-type 是 CSS 中的一个结构伪类选择器,它的作用是选中父元素下同类型元素中的第一个子元素。
例如,如果有多个 p 标签、div 标签混排,:first-of-type 会选择每个类型中第一个出现的那一个。
<article>
<h2>标题</h2>
<p>第一段文字</p>
<p>第二段文字</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/xiazai/gongju/1566">
<img src="https://img.php.cn/upload/manual/000/000/003/169232779194530.png" alt="Nextcloud Server">
</a>
<div class="aritcle_card_info">
<a href="/xiazai/gongju/1566">Nextcloud Server</a>
<p>Nextcloud服务器是一款免费且开源的服务器软件,它允许您将所有数据存储在您选择的服务器上。通过Nextcloud,您可以轻松访问和存储位于您信任的数据中心的数据,将数据在各种设备之间同步,并共享您的数据以进行协作。它提供了自托管文件同步和共享领域中最佳的安全性,并且可以通过数百个应用进行扩展。</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="Nextcloud Server">
<span>7</span>
</div>
</div>
<a href="/xiazai/gongju/1566" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="Nextcloud Server">
</a>
</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>第三段文字</p>
</article>
p:first-of-type {
color: red;
}
img:first-of-type {
border: 3px solid blue;
}
p 元素(“第一段文字”)会被设为红色,因为它是所有 p 标签中的第一个。img 元素会有一个蓝色边框。p 不是第一个子元素(h2 才是),所以 p:first-child 不会生效,但 p:first-of-type 可以。

以上就是在css中:first-of-type选择器作用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号