CSS3強大的虛擬選取器,區分相當仔細,卻也造成使用者誤解,例如 last-child 和last-of-type,同樣型式的,還有first-child/first-of-type、nth-child(n)/nth-of-type(n)、nth-last-child(n)/nth-last-of-type(n)等,這些選取結果,有時相同,有時不同,以下說明:
<H2>CSS3</h2> <div> <p>CSS3強大的虛擬選取器,區分相當仔細</p> <p>卻也造成使用者誤解</p> </div> <p>同樣型式</p> <ul> <li>last-child/last-of-type</li> <li>first-child/first-of-type</li> <li>nth-child(n)/nth-of-type(n)</li> <li>nth-last-child(n)/nth-last-of-type(n)</li> </ul>
p:last-child{color:blue;} p:first-child{color:red;} p:last-of-type{color:green;} p:first-of-type{color:cyan;} div p:first-child{color:yellow;background-color:black;}
CSS3強大的虛擬選取器,區分相當仔細
卻也造成使用者誤解
同樣型式
上例中,使用文字顏色區分選取項,整個文件的第一個標籤(first-child)是<H2>,所以 p:first-child 這個樣式指文件的風一個標籤是<p>,所以不生效。
同理,div p:first-child 是指標籤 <div> 中的第一個標籤,而且是 <p> 設為黑底黃字。
first-of-type 則是指某一種標籤的第一個,p:first-of-type 就是第一個 <p> 標籤,在本例中 <div> 裡的第一個 <p> 標籤,己經被 div p:first-child 的設定覆蓋了,否則一樣是青色,脫離了 <div> 區塊,下一個區段中的第一個 <p> 標籤,一樣顯示青色文字。
為避免有人看不到效果,結果如圖:
同意轉載,不過麻煩看一下轉載需知