Praveen Kumar
Praveen Kumar

Reputation: 236

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

Upvotes: 0

Views: 6633

Answers (2)

Matanya
Matanya

Reputation: 6346

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 */
}

Upvotes: 1

David Thomas
David Thomas

Reputation: 253308

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.

Upvotes: 3

Related Questions