今天開發的時候,發現last-child不起作用,看了下原因順便給自己學習CSS選擇器,我們這里舉個例子,如下代碼:
<div>
<h1>title</h1> <p>words</p>
<p>words</p>
<p>words</p>
</div>
當我們想獲取第一個p標簽並給它加粗時,如果采用以下寫法:
div p:first-last{font-weight:blod}
這時候我們會發現不起作用。這時候我們應該采用
div p:first-of-type{font-weight:blod}
這時候調試下就沒問題了。
這里我們要理解下:first-child和:first-of-type 區別:
:first-child 指的是父元素的第一個子元素,例如我們本例子中要使用first-child實現的話,必須把h1標簽去掉保證沒有兄弟元素,或者單獨把P標簽包圍起來;
:first-of-type 指的是父元素下相同類型子元素中的第一個,比如我們例子中的第一個p標簽。
以此類推,選擇器 :last-child 和 :last-of-type、:nth-child(n) 和 :nth-of-type(n) 也是同樣道理的。