原文:The Difference Between :nth-child and :nth-of-type
先來看一段結構簡單的 HTML:
<section>
<p>Little</p>
<p>Piggy</p>
<!--目標元素-->
</section>
以下兩種寫法在這個結構下效果完全相同:
p:nth-child(2){ color: red; }
p:nth-of-type(2){ color: red; }
結果一樣,但兩者的語意截然不同。
:nth-child 選的是同時滿足兩個條件的元素:
p:nth-of-type 的條件更少,只有一條:
p換句話說,:nth-of-type 的約束較寬鬆,也因此更不容易被結構變動弄壞。
如果在最前面插入一個 h1:
<section>
<h1>World</h1>
<p>Little</p>
<p>Piggy</p>
<!--目標元素-->
</section>
這時候 :nth-child 就「破」了:
p:nth-child(2){ color: red; } /* 選到的是 Little */
而 :nth-of-type 依然「能用」:
p:nth-of-type(2){ color: red; } /* 仍然選到 Piggy */
所謂「破」,是因為 :nth-child 現在選中的是「Little」——它同時滿足「是第二個子元素」與「是段落元素 p」這兩個條件。所謂「能用」,是因為「Piggy」依然是父元素下的第二個段落元素。
若再在 h1 之後補一個 h2,:nth-child 就完全選不到東西了,因為第二個子元素已經不再是 p;而 :nth-of-type 不受影響。
我的感覺是::nth-of-type 相對不那么脆弱,整體來說更有用,即使 :nth-child 更常被使用(這是個人意見)。你有多少次心裡想的是「我要選父元素的第二個子元素,如果它剛好是段落 p 的話」?可能有幾次,但更常見的念頭是「選第二個段落」或「每隔三列選一列」——這些情況下,:nth-of-type 是更好的工具。
我自己發現,當我抱怨「:nth-child 怎麼選不到?」時,絕大多數原因是選擇器前面加了標籤限制,而那個位置上的子元素並不是該標籤。因此使用 :nth-child 時,我建議只指定父元素,別用標籤去約束它:
dl :nth-child(2) {} /* 推薦 */
dd:nth-child(2) {} /* 不太好 */
當然,實際情況仍需具體分析。
:nth-of-type 的支援度相當不錯:Firefox 3.5+、Opera 9.5+、Chrome 2+、Safari 3.1+、IE 9+。如果需要更廣的相容性,jQuery 可以幫上忙(用 jQuery 選擇器加上類名,再以類名套用樣式,例如 $("selector:nth-child(xxxxx)").addClass("someClass"))。有趣的是,jQuery 反而放棄了對 :nth-of-type 的支援,據說理由是使用率偏低;社群有外掛可以補上這個能力。
最後別忘了它那些能幹的姊妹們::first-of-type、:last-of-type、:nth-last-of-type 與 :only-of-type。Lea Verou 做過一個視覺化示範,很適合用來建立直覺。