關於:hover這個僞類選擇器的使用方法,以前耽誤了我超多時間,測試了蠻久,拿出來講下。css
經過僞元素、僞類沒法實現子元素選擇父元素,後面的元素選擇前面的元素。學習
.grandfather { height: 300px; background: gray; } .father { height: 200px; background: blue; } .grandfather div p { margin: 0; background: yellow; border: solid 1px red; }
<div class="grandfather"> <div class="father"> <p class="chlid1" id="child1-1">1</p> <p class="chlid2">2</p> <p class="chlid3">3</p> </div> </div>
問題:從父元素向子元素選擇時:hover後面能選擇什麼?測試
/*從父元素向子元素【類名】選擇——無效*/ .father:hover .child1 { background: black; } /*從父元素向子元素【ID名】選擇——無效*/ .father:hover #child1 { background: black; } /*從父元素向子元素【標籤名】選擇——有效*/ .father:hover p { background: black; } /*從父元素向子元素選擇——有效*/ .grandfather:hover div p { background: black; } /*從父元素向子元素選擇——無效*/ .grandfather:hover .grandfather div p { background: black; }
結論: :hover後面可選擇標籤名,但不能夠選擇類名、ID名【有都不能有】。spa
問題:怎麼選擇本身?code
/*這樣選擇本身——有效*/ .grandfather:hover { background: black; } /*這樣選擇本身——有效*/ div.grandfather:hover { background: black; }
結論:選擇本身能夠使用div.類名或者直接用類名get
問題:在:hover前加一個空格會怎樣?it
/*這樣選擇——有效【可是隻針對鼠標懸浮的位置,且.grandfather不算在內】*/ .grandfather :hover { background: black; } /*這樣選擇子元素——無效*/ .grandfather :hover div p { background: black; }
結論:能夠在:hover前加空格,可是它以後不可再用別的標籤。io
:hover後面可選擇標籤名,但不能夠選擇類名、ID名【有都不能有】。class
選擇本身能夠使用div.類名或者直接用類名方法
能夠在:hover前加空格,可是它以後不可再用別的標籤。