CSS3選擇器「:nth-child()」與「:nth-of-type()」用法大不同
![梅問題-CSS教學-CSS3選擇器「nth-child與nth-of-type」大不同](https://ds.minwt.com.tw/img/Content/CSS/css3-nth-child-nth-of-type/nth-child-nth-of-type_00.jpg)
CSS3-:nth-child()
當網頁中有4個p標籤時,可用 nth-child的方式,來進行選擇,當下odd表示,只要是單數列背景就會套用成淺灰色。
![梅問題-CSS教學-CSS3選擇器「nth-child與nth-of-type」大不同](https://ds.minwt.com.tw/img/Content/CSS/css3-nth-child-nth-of-type/nth-child-nth-of-type_01.jpg)
這時候只要是奇數列的p標籤,背景就會變成淺灰色,在這種情況下,即便使用nth-of-type也會得到一樣的效果。
![梅問題-CSS教學-CSS3選擇器「nth-child與nth-of-type」大不同](https://ds.minwt.com.tw/img/Content/CSS/css3-nth-child-nth-of-type/nth-child-nth-of-type_02.jpg)
改變一下網頁的架構,把p標籤下方,加入<hr>來將區塊與區塊間來畫一條。
![梅問題-CSS教學-CSS3選擇器「nth-child與nth-of-type」大不同](https://ds.minwt.com.tw/img/Content/CSS/css3-nth-child-nth-of-type/nth-child-nth-of-type_03.jpg)
這時就會看到,全有p標籤的背景都變成淺灰色的了。
![梅問題-CSS教學-CSS3選擇器「nth-child與nth-of-type」大不同](https://ds.minwt.com.tw/img/Content/CSS/css3-nth-child-nth-of-type/nth-child-nth-of-type_04.jpg)
原因就出在,當使用nth-child時,它並不是只篩選p標籤,而是網頁中的所有標籤都會一起計算,所以可看到,這時所有的p就變成奇數列了。
![梅問題-CSS教學-CSS3選擇器「nth-child與nth-of-type」大不同](https://ds.minwt.com.tw/img/Content/CSS/css3-nth-child-nth-of-type/nth-child-nth-of-type_05.jpg)
CSS3-:nth-of-type()
這時只要把原本的nth-child改成nth-of-type,就只會針對網頁中的p標籤進行篩選。
![梅問題-CSS教學-CSS3選擇器「nth-child與nth-of-type」大不同](https://ds.minwt.com.tw/img/Content/CSS/css3-nth-child-nth-of-type/nth-child-nth-of-type_06.jpg)
鏘~鏘~這時候就只有在奇數列的p標籤的背景才會套用淺灰色 。
转自:https://www.minwt.com/webdesign-dev/css/10885.html