常用的css 選擇器:
class .
id #
元素選擇器
p :所有p元素
div,p :所有div+p元素
div p :選擇Div內的所有p元素, 包裹無限級 孫子級別等…
div>p :選擇父級是DIV的所有 p元素 記住:孫子輩不算
div+p :選擇所有緊接着div元素之後的p元素 (少用)
屬性選擇器:
[target] :選擇所有帶有target屬性元素
[target=blank] 選擇所有 target=”blank“屬性的所有元素
[title~=m] 選擇標題屬性包含”M“的所有元素
僞類選擇:
a:link= 選擇所有未訪問過的鏈接
a:visited= 訪問過的
a:active=活動鏈接
a:hover = 鼠標在連接上面
input:focus =獲取焦點
CSS3 高級選擇器
p:first-of-type 選擇每個P元素其父元素的第一個P元素(選擇同背元素)
p:first-of-type{
background:#f55;
}
<div>
<h4>這個不是p元素,所以沒有被選擇</h4>
<p>第一個P元素</p>
<p>第二個P元素</p>
<p>第三個P元素</p>
</div>
p:last-of-type :選擇p元素父級別的最後一個p元素(說白了就是同背元素)
p:first-child :選擇:p元素是第一個元素,則符合要求,如果不是則不符合
<style>
p:first-child{
background:red;
}
</style>
<div>
<a>我是第一個元素 但是我不是P元素</a>
<p>我是第一個p元素,但是我不在父級第一個</p>
<p>我是第二個p元素</p>
</div>
<div>
<p>我是第一個元素 同時我是p元素</a>
<a>我是第一個a元素,</a>
<p>我是第二個p元素</p>
</div>
運行結果:
歸納簡單的理解:
p:first-of-type :找出同輩的第一個p
p:first-child :第一個必須是p
p:nth-of-type(1) =找到第一個p元素
p:nth-of-type(2):找到第二個p元素(如圖)
p:nth-of-type(3):找到第三個p
p:first-of-type :找到第一個P元素
其實 first-of-type=nth-of-type(1) 都表示找到一個P元素
畫重點:p:nth-child(1) 表示:第一個元素=p元素的標紅
p:nth-child(2) =第二個元素=p元素的 標紅
p:nth-child(3)第三個元素=p元素的標紅
歸納總結:
nth-of-type(N) 和nth-child(N)的區別
p:nth-of-type(N):選擇第N個P元素
p:nth-child(N) :選擇第N個元素=P的元素