change background of parent div on hover

前端 未结 6 1196
情书的邮戳
情书的邮戳 2020-12-31 13:05

I have this code:

6条回答
  •  抹茶落季
    2020-12-31 13:34

    Solution: The solution is to use Absolute Positioning. See the Snippet below. Adding an ID of "orangeImg" makes life a little easier!

    Create a holder div with relative positioning. Inside this div place your "orangeImg" and "orangeBG" divs. Both will have positioning of absolute. The orangeBG div will also need to be given width and height properties as it won't contain any elements. Using the z-index property you will layer the divs, with the Img div on top.

    Adding a .target class to the orangeBG div, you can then use the sibling selector "~" to then select any sibling of the orangeImg div on hover. The only sibling here is the orangeBG div. Therefore the background will change, only when the image is hovered! JSfiddle here

    Best of luck,

    Alan

    #holder {position: relative; width: 200px; height:100px;}
    #orangeImg {position:absolute; top:10px; right:10px; z-index:9999;}
    #orangeBG {position:absolute; top:0px; right:0px; z-index:1; background-color:#353;width: 200px; height:100px;}
    #orangeImg:hover ~ .target {background-color:#621;}

提交回复
热议问题