How to apply a style to two different elements using :Hover?

Asked

Viewed 3,583 times

5

Considering:

HTML

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

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

CSS

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

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

  • You want the #div2 background to change when you hover over #div1 (returning to normal on exit)?

  • @Wakim, exactly.

  • I deleted my answer, I didn’t mean the question, I think @Wakim already answered what you needed ^^

1 answer

8


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

Using the brother selector (General Sibling Selector) "~" you can apply the rule of hover on the brother whose selector is on the right. Thus the rule is:

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

Reading the rule would be:

When mouse over element with id div1, select all brothers 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 brother selector "+" that only picks up the subsequent siblings and antecedent to the elements of the left selector, can be useful as well.

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

For more details of 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
  • Perfect answer, but just to clarify, the ~ takes all selectors on the same level and the + takes the selectors that are immediately above and below?

  • 1

    Exactly, but you need to think about trees (DOM is a tree), correct about the ~, in the case of + they are on the same level, but roughly it is the "left" and "direct" node in the sub-tree that make up all the brothers.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.