0

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

Aiias
  • 4,683
  • 1
  • 18
  • 34
Praveen Kumar
  • 206
  • 4
  • 14

2 Answers2

3

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.
David Thomas
  • 249,100
  • 51
  • 377
  • 410
1

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 */
}
Matanya
  • 6,233
  • 9
  • 47
  • 80
  • Help me with this http://stackoverflow.com/questions/17487499/change-multiple-div-style-when-hover-on-another-div-using-css – Praveen Kumar Jul 05 '13 at 11:17