:nth-child 是 CSS 中很實用的結構選擇器。只要理解 n 與表達式的含義,就能精準選取列表或重複元素中的特定項目。
若要選取列表中的第五個項目,可直接使用 nth-child(5)。

li:nth-child(5) { color: green; }
若要選第一個,也可使用 :first-child。

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

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

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

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

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

li:last-child { color: green; }

li:nth-last-child(2) { color: green; }
瀏覽器支援方面,:first-child 與 :last-child 支援較早,其餘:nth-child 表達式在較新瀏覽器中才有完整支援。若需兼顧舊版 IE,可搭配 Selectivizr 等工具。