前端學習總結【101天】:CSS——關於僞類hover選擇器的測試

隨便叨叨

關於:hover這個僞類選擇器的使用方法,以前耽誤了我超多時間,測試了蠻久,拿出來講下。css

學習總結

經過僞元素、僞類沒法實現子元素選擇父元素,後面的元素選擇前面的元素。學習

1、初始代碼

.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>

2、測試代碼

測試1


  • 問題:從父元素向子元素選擇時: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

測試2


  • 問題:怎麼選擇本身?code

    /*這樣選擇本身——有效*/
    .grandfather:hover {
        background: black;
    }
    
    /*這樣選擇本身——有效*/
    div.grandfather:hover {
        background: black;
    }
  • 結論:選擇本身能夠使用div.類名或者直接用類名get

測試3


  • 問題:在:hover前加一個空格會怎樣?it

/*這樣選擇——有效【可是隻針對鼠標懸浮的位置,且.grandfather不算在內】*/
    .grandfather :hover {
        background: black;
    }

    /*這樣選擇子元素——無效*/
    .grandfather :hover div p {
        background: black;
    }
  • 結論:能夠在:hover前加空格,可是它以後不可再用別的標籤。io

3、我的總結

  • :hover後面可選擇標籤名,但不能夠選擇類名、ID名【有都不能有】。class

  • 選擇本身能夠使用div.類名或者直接用類名方法

  • 能夠在:hover前加空格,可是它以後不可再用別的標籤。

4、參考資料

關於css中hover的用法,如何編寫代碼才能完成下面的功能?仍是說不能完成?

相關文章
相關標籤/搜索