Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

html - Change parent div to a different background when hovering over individual child divs

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...