在css3中有兩個新的選擇器可以選擇父元素下對應的子元素,一個是:nth-child 另一個是:nth-of-type。 但是它們到底有什么區別呢?
其實區別很簡單::nth-of-type為什么要叫:nth-of-type?因為它是以"type"來區分的。也就是說:ele:nth-of-type(n)是指父元素下第n個ele元素,
而ele:nth-child(n)是指父元素下第n個元素且這個元素為ele,若不是,則選擇失敗。
而ele:nth-child(n)是指父元素下第n個元素且這個元素為ele,若不是,則選擇失敗。
文字未免聽起來比較晦澀,便於理解,這里附上一個小例子:
<!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>
結果如下:

上面這個例子,.demo li:nth-child(2)選擇的是<li>one</li>節點,而.demo li:nth-of-type(2)則選擇的是<li>two</li>節點。
但是如果在nth-child和 nth-of-type前不指定標簽呢?
<style> .demo :nth-child(2) { color: #ff0000; } .demo :nth-of-type(2) { color: #00ff00; } </style>
這樣又會是什么結果呢,看下html結構:
<ul class="demo"> <p>first p</p> <li>first li</li> <li>second li</li> <p>second p</p> </ul>

如上可見,在他們之前不指定標簽類型,:nth-child(2) 選中依舊是第二個元素,無論它是什么標簽。而 :nth-type-of(2) 選中了兩個元素,分別是父級.demo中的第二個p標簽和第二個li標簽,由此可見,不指定標簽類型時,:nth-type-of(2)會選中所有類型標簽的第二個。
我們已經了解了nth-child和 nth-of-type的基本使用與區別,那么更進一步nth-of-type(n)與nth-child(n)中的n是什么呢?
數字:也就是上面例子的使用,就不做贅述。
關鍵詞:Odd 、even
Odd 和 even 是可用於匹配下標是奇數或偶數的子元素的關鍵詞
注意:第一個子元素的下標是 1
在這里,我們為奇數和偶數 p 元素指定兩種不同的背景色:
<style> p:nth-of-type(odd) { background: #ff0000; } p:nth-of-type(even) { background: #0000ff; } </style>
公式:或者說是算術表達式
使用公式 (an + b)。描述:表示周期的長度,n 是計數器(從 0 開始),b 是偏移值。在這里,我們指定了下標是 3 的倍數的所有 p 元素的背景色:
<style> p:nth-of-type(3n+0) { background: #ff0000; } </style>
若是 :nth-of-type(4n+2) 就是選擇下標是4的倍數加上2的所有元素