譯自:Useful :nth-child Recipes
每次想「完美」用上 :nth-child 或 :nth-of-type 時總有點頭暈。但牠們的規則其實很有邏輯——越理解,寫出的 CSS 選擇器就越精準。
以下這些「配方」其實就是一堆表達式。為了示範方便,我一律用同一份清單並標上數字,你很容易把它們改寫成適用於自己結構的版本。

li:nth-child(5){ color: green; }
若要選第一個,可以直接用 :first-child,當然改寫上面的表達式也行。

li:nth-child(n+6){ color: green; }
如果元素超過 10 個,它會把第 6 個之後的一併選中。

li:nth-child(-n+5){ color: green; }

li:nth-child(4n-7) { /* 或寫成 4n+1 */ color: green; }

li:nth-child(odd){ color: green; }

li:nth-child(even){ color: green; }
當然,這兩種效果也可以用 2n+1 與 2n 來寫。

li:last-child { color: green; }

li:nth-last-child(2){ color: green; }
由此可見,上一節的效果其實還有另一種寫法。
有個耐人尋味的細節::first-child 與 :last-child 在 IE7 就已支援,但其他的結構偽類要等到 IE9。如果你必須兼顧舊版 IE,可以考慮 Selectivizr;若相容性對專案很重要,記得查一下「Can I use」這類網站。
用 CSS3 選擇器其實挺有意思的,有點像在解簡單的數學題——一旦想通那條公式,選擇元素就變成一氣呵成的事。