Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm seeing the solutions to accomplish this when dealing with only one desired hover effect, but I want to have four child divs that each change the main parent div's background to a separate image.

I'm assuming this isn't possible with CSS.

<div id="buttonBox">
   <div id="schedBox">
     <a href="#">Schedule</a>
   </div>
   <div id="transBox">
     <a href="#">Transformation</a>
   </div>
   <div id="destBox">
     <a href="#">Destination</a>
   </div>
   <div id="inspirBox">
     <a href="#">Inspiration</a>
   </div>
</div>

Alternatively, I could have the child divs each have a different background. Hovering one child div would change all child div backgrounds to a separate colour, but I couldn't figure out how to have a hover on the 2nd div affect the previous div.. only subsequent siblings.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

While the actual parent selector is not possible through CSS, you can “hack” it for your case using extra elements and positioning.

What you need is to change the background based on what element is hovered — ok! Let's add pseudo-elements (or normal elements if you'll need IE support) and position them over the parent using absolute positioning and positive z-index:

#buttonBox {
    position: relative;
    z-index: 1;
}

#buttonBox > div:before {
    content: "";

    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: -1;
}

Those positioned elements should have negative z-index, so they would be placed under all other content, but over the parent element's background.

This way you could add rules like

#schedBox:hover:before  { background: lime;   }
#transBox:hover:before  { background: red;    }
#destBox:hover:before   { background: orange; }
#inspirBox:hover:before { background: yellow; }

And the pseudo-background of the parent would change on hover!

The only thing to know is that there shouldn't be any elements with non-static position between the parent and the elements with the background role.

Here is the live example at dabblet


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...