:nth-child

套用一或多個樣式至作為其父元素第 n 個子項的元素。

語法

:nth-child (n) { sRules }

可能的值

n

運算式,這個運算式會在同一父元素底下,選取其編號是 n 的倍數的所有子元素。

sRules

指定一或多個階層式樣式表 (CSS) 屬性/值組的字串。

備註

決定要選取哪些元素的運算式可以採用下列其中一種格式:

  • even :選取編號為偶數的元素例項。

  • odd :選取編號為奇數的元素例項。

  • a**n+**b:從第 a+b 個元素例項開始,選取其編號是 a 的倍數的所有例項。

  • an-b:從第 a-b 個元素例項開始,選取其編號是 a 的倍數的所有例項。

:nth-child 虛擬類別是結構性虛擬類別。結構性虛擬類別可在無法使用簡單選取器或結合器選取項目的文件樹狀目錄中,根據額外的資訊執行選取動作。

範例

下列樣式規則會在文件樹狀目錄中每個 H1 的前面和後面插入大括號。

p:nth-child(3n+1)   /* selects every third paragraph, starting from paragraph one */
p:nth-child(4n-1)   /* selects every fourth paragraph, starting from paragraph three */
p:nth-child(5n+0)   /* selects every fifth paragraph, starting from paragraph five.

標準資訊

您可以在 CSS Selectors Level 3 (CSS 選取器層級 3) Gg721782.xtlink_newWindow(zh-tw,Expression.40).png 找到此虛擬類別的定義。

適用範圍

a , abbr , acronym , address , b , big , blockquote , body , caption , center , cite , code , col , colgroup , dd , dfn , dir , div , dl , dt , em , form , hn , html , i , img , input , input type=button , input type=checkbox , input type=file , input type=hidden , input type=image , input type=password , input type=radio , input type=reset , input type=submit , input type=text , kbd , label , legend , li , listing , marquee , menu , ol , p , plaintext , pre , s , samp , select , small , span , strike , strong , sub , sup , table , tbody , td , textarea , tfoot , th , thead , tr , tt , u , ul , var , xmp

另請參閱

概念

:empty
:first-child
:first-of-type
:last-child
:last-of-type
:nth-last-child
:nth-last-of-type
:nth-of-type
:only-child
:only-of-type
:root