简体   繁体   中英

change multiple div style when Hover on another Div using CSS

When I Hover on #main, Style of #box and #box2 want to change. But it is not working.

Html code is

<div id="main">Main</div>
<div id="box">Text</div>
<div id="box1" >Text1</div>

Css is

#main:hover + #box,#box1 {
    background-color: green;
}

Here is the demo link

I'd suggest the following:

#main:hover + #box,
#main:hover ~ #box1 {
    /* CSS */
}

JS Fiddle demo .

The problems you had, originally, were the two selectors:

#main:hover + #box,
#box1 {
    background-color: green;
}

The first of which worked, unfortunately the comma separates entire selectors, it doesn't give a comma-separated list of descendants/siblings to be affected. So the #box1 was always background-colored, rather than just on :hover of #main .

The combinators I've used are the adjacent-sibling combinator ( + ) and the general-sibling combinator ( ~ ), the latter of which will affect any later sibling of #main that has the given id of box1 .

The second rule, written with ~ could be rewritten by specifying the exact sequence of elements using multiple (in this case two) adjacent-sibling combinators, to give:

#main:hover + #box,
#main:hover + #box + #box1 {
    /* CSS */
}

But this does become increasingly fragile over time, and maintenance becomes more trying when the HTML structure changes, or new elements are inserted between the relevant elements.

References:

  • CSS Selectors.

probably cleaner to use a class and the general sibling selector (~):

HTML:

<div id="main">Main</div>
<div class="box">Text</div>
<div class="box" >Text1</div>

CSS:

#main:hover ~ .box {
    /* CSS */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM