How to apply a style on two different elements using: hover?

5

Considering:

HTML

<div id="div1">
    <p>Elemento 1</p>
</div>
<div id="div2">
    <p>Elemento 2</p>
</div>

How can I use :hover in div1 to change style properties of div2 ? I tried the following, but to no avail:

CSS

#div2, #div1:hover {
    background-color: white;
}

By the time the mouse goes into div1 , it works the way I want, but when it exits a problem arises: div2 continues with background-color: white . What should I do (using CSS) to make the white background of div2 fade along with the white background of the other div?

    
asked by anonymous 26.07.2014 / 03:11

1 answer

8

The problem is that you are applying the same rule to two independent selectors, using the "," no relationship is created between the selectors.

Using the General Sibling Selector "~" you can apply the hover rule to the brother whose selector is to the right. That way the rule stays:

#div1:hover ~ #div2 {
    background-color: white;
}

Reading the rule would be:

  

When you hover over the element with id div1 , select all siblings whose id is div2 and apply the rule below.

Take a look at this JSFiddle to see the code working. In case I put the black background to have contrast.

There is a variation, the direct sibling selector "+" that takes only the siblings subsequent and antecedent to the elements of the left selector, can be useful as well.

In addition to these, there is also the Child Selector ">", it can also be used, but not for this specific case. And the descender selector ("space"), which is more comprehensive than the child selector.

For more details see:

  • link
  • link
  • link
  • link
  • 26.07.2014 / 03:29