:nth-of-type选择器根据元素类型和同类型兄弟位置匹配,n可为数字、even/odd或an+b公式,如p:nth-of-type(2)选中第二个p;与:nth-child不同,它只计同类标签;常用于表格隔行变色tr:nth-of-type(even)、首段加大p:nth-of-type(1)等场景,IE9+支持,n从1开始,需确保目标存在。

CSS中的 :nth-of-type 选择器用于选中父元素下特定类型的第n个子元素。它根据元素的类型(标签名)和在同类型兄弟元素中的位置来匹配,非常适合对某类标签进行精确控制,比如只选中第2个、第4个p标签,或每隔一个div添加样式。
:nth-of-type(n) 中的 n 可以是数字、关键字(如 even、odd)或公式(an + b)。选择器会先筛选出指定类型的元素,再按它们在文档流中的顺序进行计数。
例如:p:nth-of-type(2):选中父元素中第二个 p 元素div:nth-of-type(even):选中偶数位置的 divli:nth-of-type(3n+1):从第1个开始,每3个li选一个(1, 4, 7...)关键在于匹配逻辑不同。:nth-child 是基于所有子元素的位置,而 :nth-of-type 只看同类型元素的位置。
举例说明:<div><p>段落1</p><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><span>其他标签</span><p>段落2</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1971">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175679994166405.png" alt="如知AI笔记">
</a>
<div class="aritcle_card_info">
<a href="/ai/1971">如知AI笔记</a>
<p>如知笔记——支持markdown的在线笔记,支持ai智能写作、AI搜索,支持DeepseekR1满血大模型</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="如知AI笔记">
<span>27</span>
</div>
</div>
<a href="/ai/1971" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="如知AI笔记">
</a>
</div>
<!-- 这是第2个p,也是p:nth-of-type(2) --></div>此时 p:nth-of-type(2) 能选中“段落2”,但 p:nth-child(2) 不会生效,因为第二个子元素是 span,不是 p。
在实际开发中,:nth-of-type 常用于列表、表单、排版等需要差异化样式的场景。
tr:nth-of-type(even) { background: #f0f0f0; }
p:nth-of-type(1) { font-size: 1.2em; }
button:nth-of-type(3) { margin-left: 10px; }
该选择器在现代浏览器中支持良好,IE9及以上版本均支持。使用时注意以下几点:
基本上就这些。掌握 :nth-of-type 能让你更精细地控制页面结构,避免添加多余类名,让CSS更简洁高效。
以上就是如何在CSS中实现nth-of-type选择器_特定类型元素控制的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号