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

Question:

Whereas:

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 without success:

CSS

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

Until the moment the mouse enters the div1 , it works as I want, however when it leaves a problem arises: the div2 continues with the background-color: white . What should I do (using CSS) to make the white background of the div2 disappear along with the white background of the other div?

Answer:

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

Using the sibling selector (General Sibling Selector) "~" you can apply the hover rule to the sibling whose selector is on the right. So the rule is:

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

Reading the rule would be:

When hovering 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 this case, I put the background in black for contrast.

There is a variation, the "+" direct sibling selector which 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 ">", which can be used as well, but not for this specific case. And the Descendant Selector " " (space), which is wider than the child selector.

For more details have a look at:

  1. https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_selectors
  2. https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_selectors
  3. https://developer.mozilla.org/en-US/docs/Web/CSS/Child_selectors
  4. https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_selectors
Scroll to Top