DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> DIV十CSS布局 >> 布局實例
CSS :nth-child 選擇器使用指南
編輯:布局實例     

: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 等工具。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved