Reputation: 236
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
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
Reputation: 253308
I'd suggest the following:
#main:hover + #box,
#main:hover ~ #box1 {
/* CSS */
}
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:
Upvotes: 3