:nth-child(n) 選擇器匹配屬于其父元素的第 N 個(gè)子元素,不論元素的類型。
n 可以是數(shù)字、關(guān)鍵詞或公式。
提示:請(qǐng)參閱 :nth-of-type() 選擇器,該選擇器選取父元素的第 N 個(gè)指定類型的子元素。
所有主流瀏覽器均支持 :nth-child() 選擇器,除了 IE8 及更早的版本。
規(guī)定屬于其父元素的第二個(gè)子元素的每個(gè) p 的背景色:
p:nth-child(2)
{
background:#ff0000;
}
:nth-child(2)選取第幾個(gè)標(biāo)簽,“2可以是你想要的數(shù)字”
.demo01 li:nth-child(2){background:#090}
:nth-child(n+4)選取大于等于4標(biāo)簽,“n”表示從整數(shù),下同
.demo01 li:nth-child(n+4){background:#090}
:nth-child(-n+4)選取小于等于4標(biāo)簽
.demo01 li:nth-child(-n+4){background:#090}
:nth-child(2n)選取偶數(shù)標(biāo)簽,2n也可以是even
.demo01 li:nth-child(2n){background:#090}
:nth-child(2n-1)選取奇數(shù)標(biāo)簽,2n-1可以是odd
.demo01 li:nth-child(2n-1){background:#090}
:nth-child(3n+1)自定義選取標(biāo)簽,3n+1表示“隔二取一”
.demo01 li:nth-child(3n+1){background:#090}
:last-child選取最后一個(gè)標(biāo)簽
.demo01 li:last-child{background:#090}
:nth-last-child(3)選取倒數(shù)第幾個(gè)標(biāo)簽,3表示選取第3個(gè)
.demo01 li:nth-last-child(3){background:#090}
ok,:nth-child的這些用法在實(shí)際中很用得著,不用單獨(dú)給需要選取的標(biāo)簽加上ID或Class!
如對(duì)本文有疑問,請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答!! 點(diǎn)擊進(jìn)入論壇