1. 程式人生 > >nth-child,nth-last-child,only-child,nth-of-type,nth-last-of-type,only-of-type,first-of-type,last-of-type,first-child,last-child偽類區別和用法

nth-child,nth-last-child,only-child,nth-of-type,nth-last-of-type,only-of-type,first-of-type,last-of-type,first-child,last-child偽類區別和用法

type nth 只有一個 not 同時 選擇器 -type span 進行

我將這坨偽類分成三組,第一組:nth-child,nth-last-child,only-child第二組:nth-of-type,nth-last-of-type,第三組:first-of-tpye,last-of-type,第四組:first-child,last-child。

==1==

nth-child定義是:其父級的第x個子元素。寫法有兩種:

p :nth-child(x)

p:nth-child(x)

第一種指的是p的第x個子元素,無需查找,明確指明父級,而子級無論是什麽元素都將被選擇。

第二種指的是p的父級元素的第x個子元素,此時父級元素並未指定,是該選擇器去查詢的包含有p元素的父級容器,但此時nth-child選擇類型被明確指定了,只能是p元素,因此就會出現從p的父級去查找其子元素的時候,找不到p:nth-child(x)的情況,因為此時是在p的父級元素底下對所有子元素進行索引,x對應的p只有都具備的時候該選擇器才能選中元素,換句話說,p的父級下的子元素,只有同時符合既是p元素且索引正好是x,才能被選中。

搞清楚了哈。再說說nth-child括號內可以允許的參數,包括數值,關鍵詞(odd,even)及公式。

數值很好說,就是子元素的索引,該索引不單單指特定元素,而是所有子元素。關鍵詞當然也是子元素的奇偶索引,因為含一個單子元素的情況很多見,因此奇數總是多於偶數比較常見。

公式,an+b,a,b是常數,而n是自然數,也就是0到無窮,變種2n+1,3n+1,-n+7(7以前的數字),而若數字x為n代表所有元素。關於求交並補集,以下兩篇博文寫的很清楚,不贅述:

http://www.qdfuns.com/notes/17398/84081c84d8c2056c6f4935c3c7fc6bbf:storey-13.html

http://www.qdfuns.com/notes/17398/f5371a84f07992c180561e0272bf800c.html

http://www.qdfuns.com/notes/17398/fa3777cd51a94d7ab30c87bd479a1471.html

nth-last-child跟nth-child一樣,一個正序,一個倒序,而only-child指的是僅僅含有某指定元素或者未指定但是只有一個子元素的。

==2==

第二組,first-chlid和last-child,是nth-child(1)和nth-last-child(1)的簡寫 ,不贅述。

==3==

第三組nth-of-type,nth-last-of-type,last-of-type,first-of-type,only-of-type。

nth-of-type,nth-last-of-type,可以分別從前到後和從後到前選一組,而first-of-type和last-of-type則只能選第一個和最後一個。相對於第一組,它們的區別在於:

p :nth-of-type(1)

p:nth-of-type(1)

前者會選擇所有第一次出現的不同子元素的第一個。比如有10個子元素,其中a3個,span2個,p3個,div一個,em一個,則會將a,span和p的第一個選中,div和em也被選中。因此nth-of-type的最佳用途肯定不是這樣使用。而第二種用法則會將p的父級元素下的所有子元素種的第一個選中,索引不會計算其他非p元素。

大概就這麽多。反正我懂了。其他遇到再說。

nth-child,nth-last-child,only-child,nth-of-type,nth-last-of-type,only-of-type,first-of-type,last-of-type,first-child,last-child偽類區別和用法