:nth-of-type(n)比:nth-child(n)更可靠,因其仅统计同标签兄弟元素,忽略注释、换行、空格及异构节点;而:nth-child(n)对所有子节点统一编号,易受HTML结构干扰。

直接用 :nth-of-type(n),别用 :nth-child(n) —— 后者在表格、富文本或 CMS 渲染场景下极易失效。
为什么 :nth-of-type() 比 :nth-child() 更可靠
因为 :nth-of-type() 只统计同标签名的兄弟元素,完全跳过 <div>、<code><span></span>、注释、换行符甚至空格文本节点。而 :nth-child() 是对父元素下所有子节点(含不可见节点)统一编号,HTML 里多一个换行或 CMS 插入一个 <figure></figure>,目标就偏了。
常见错误现象:tr:nth-child(2) 想选第二行,结果选中了 <thead> 里的 <code><tr>;<code>p:nth-child(3) 失效,实际检查发现第一个子节点是 HTML 注释 <!-- intro -->,真正的第一个 <p></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/code/12093" title="CSS婚礼策划服务机构宣传网站模板"><img
src="https://img.php.cn/upload/webcode/000/000/018/178607072210981.jpg" alt="CSS婚礼策划服务机构宣传网站模板" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/code/12093" title="CSS婚礼策划服务机构宣传网站模板" class="overflowclass">CSS婚礼策划服务机构宣传网站模板</a>
<p class="overflowclass">CSS婚礼策划服务机构宣传网站模板是一款适合提供婚礼策划和婚庆服务机构宣传网站模板下载。提示:本模板调用到谷歌字体库,可能会出现页面打开比较缓慢。</p>
</div>
<a rel="nofollow" href="/xiazai/code/12093" title="CSS婚礼策划服务机构宣传网站模板" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div> 是第 2 个子节点。
- 表格中定位单元格:用
tr:nth-of-type(3) td:nth-of-type(2),不是tr:nth-child(3) td:nth-child(2) - 富文本段落控制:CMS 输出常混有
<blockquote></blockquote>、<hr>,p:nth-of-type(1)稳定命中首段 - 兼容性无顾虑:IE9+ 全支持,无需 polyfill
:nth-of-type() 的合法参数写法
n 必须是 ≥ 1 的正整数,或符合 an + b 形式的表达式(n 从 0 开始代入,结果必须 ≥ 1)。浏览器不会“自动取最近有效值”,写错就完全不匹配。
-
p:nth-of-type(1)→ 第一个<p></p>(等价于p:first-of-type) -
li:nth-of-type(even)→ 所有偶数位的<li>(即第 2、4、6…个<li>) -
td:nth-of-type(3n+1)→ 第 1、4、7…列的<td><li> <code>div:nth-of-type(-n+3)→ 前 3 个<div>(n=0→3, n=1→2, n=2→1)<li> <code>div:nth-of-type(999)→ 危险!DOM 动态增删后极易断样式,应改用div:last-of-type或加 class
表格中精准控制单个单元格的典型写法
表格结构天然混排 <th> 和 <code><td>,<code>:nth-child() 在这种场景下基本不可信。必须分层用 :nth-of-type():
想给「第 4 行第 2 列的普通单元格」加背景色:tr:nth-of-type(4) td:nth-of-type(2)
想给「第 1 行第 3 列的表头」加粗:tr:nth-of-type(1) th:nth-of-type(3)
注意:th 和 td 是不同类型,互不影响计数;tr:nth-of-type(2) 会跳过 <thead> 或 <code><tfoot> 里的 <code><tr>,只在当前 <code><tbody> 内计数 —— 这正是你想要的。<p>性能与可维护性提醒:复杂表达式如 <code>td:nth-of-type(5n+2) 在超大表格(>5000 行)中可能轻微影响渲染,但日常业务表格完全无感;真正容易被忽略的是动态插入内容后索引偏移——如果 JS 后续往表格里 append() 新行,原有 :nth-of-type(5) 仍指“第五个 <tr>”,不是视觉上第五行,这点必须心里有数。</tr>










