CSS3中nth-child與nth-of-type的區(qū)別其實(shí)很簡(jiǎn)單::nth-of-type為什么要叫:nth-of-type?因?yàn)樗且?quot;type"來(lái)區(qū)分的。也就是說(shuō):ele:nth-of-type(n)是指父元素下第n個(gè)ele元素, 而ele:nth-child(n)是指父元素下第n個(gè)元素且這個(gè)元素為ele,若不是,則選擇失敗。
文字未免聽起來(lái)比較晦澀,便于理解,這里附上一個(gè)小例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> </head> <style> .demo li:nth-child(2){ color: #ff0000; } .demo li:nth-of-type(2){ color: #00ff00; } </style> <body> <div> <ul class="demo"> <p>zero</p> <li>one</li> <li>two</li> </ul> </div> </body> </html>
結(jié)果如下:
上面這個(gè)例子,.demo li:nth-child(2)選擇的是<li>one</li>節(jié)點(diǎn),而.demo li:nth-of-type(2)則選擇的是<li>two</li>節(jié)點(diǎn)。
但是如果在nth-child和 nth-of-type前不指定標(biāo)簽?zāi)兀?/p>
.demo :nth-child(2){ color: #ff0000; } .demo :nth-of-type(2){ color: #00ff00; }
這樣又會(huì)是什么結(jié)果呢,看下html結(jié)構(gòu):
<ul class="demo"> <p>first p</p> <li>first li</li> <li>second li</li> <p>second p</p> </ul>
結(jié)果:
如上可見,在他們之前不指定標(biāo)簽類型,:nth-child(2) 選中依舊是第二個(gè)元素,無(wú)論它是什么標(biāo)簽。而 :nth-type-of(2) 選中了兩個(gè)元素,分別是父級(jí).demo中的第二個(gè)p標(biāo)簽和第二個(gè)li標(biāo)簽,由此可見,不指定標(biāo)簽類型時(shí),:nth-type-of(2)會(huì)選中所有類型標(biāo)簽的第二個(gè)。
我們已經(jīng)了解了nth-child和 nth-of-type的基本使用與區(qū)別,那么更進(jìn)一步nth-of-type(n)與nth-child(n)中的n是什么呢?
nth-of-type(n)與nth-child(n)中的n可以是數(shù)字、關(guān)鍵詞或公式。 數(shù)字:也就是上面例子的使用,就不做贅述。 關(guān)鍵詞:Odd 、even
Odd 和 even 是可用于匹配下標(biāo)是奇數(shù)或偶數(shù)的子元素的關(guān)鍵詞
注意:第一個(gè)子元素的下標(biāo)是 1
在這里,我們?yōu)槠鏀?shù)和偶數(shù) p 元素指定兩種不同的背景色:
p:nth-of-type(odd) { background:#ff0000; } p:nth-of-type(even) { background:#0000ff; }
公式:或者說(shuō)是算術(shù)表達(dá)式
使用公式 (an + b)。描述:表示周期的長(zhǎng)度,n 是計(jì)數(shù)器(從 0 開始),b 是偏移值。
在這里,我們指定了下標(biāo)是 3 的倍數(shù)的所有 p 元素的背景色:
p:nth-of-type(3n+0) { background:#ff0000; }
若是 :nth-of-type(4n+2) 就是選擇下標(biāo)是4的倍數(shù)加上2的所有元素
總結(jié)
以上就是關(guān)于css3中nth-child和 nth-of-type區(qū)別的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家學(xué)習(xí)或者使用CSS3能有一定的幫助,如果有疑問大家可以留言交流。