2

I want to change div element's color by other div element's hover. I've tried this, but it doesn't works. HTML:

<div class="test1">
    <p></p>
</div>
<div class="test2">
    <a> 
      <span></span>
    </a>
</div>

and CSS:

p:hover ~ a
{
 filter: hue-rotate(110deg);
}
a
{
 color: #03e9f4;
}

For sure, it works with HTML like this...

<div class="test1">
    <p></p>
    <a> 
      <span></span>
    </a>
</div>

but I want it in two other divs, is it possible?

Melodysso
  • 29
  • 2

1 Answers1

3

The reason it works in the last example is that the hovered element and target element are siblings within the same div (and you are using the general sibling combinator "~")- the only way to achieve that is to have the hover pseudostate on the first div and use the same logic to target the second div and then into the second div to the a element via the descendant selector (" ").

There is no way in CSS alone to achieve the effect when you hover over the p - it has to be the parent element that is the sibling. You could easily do this with JS - but not with only CSS.

The following will change the color of the a element when you hover over the parent div of the p. I also added a little :after pseudo-element to demonstrate the hovering result better.

a {
 color: #03e9f4;
}

.test1:hover ~ .test2 a {
 filter: hue-rotate(110deg);
}

.test1:hover ~ .test2 a:after {
  content: ' and my color changed because you hovered over the previous div'
}
<div class="test1">
    <p>I am in the first div</p>
</div>
<div class="test2">
    <a> 
      <span>I am in the second div</span>
    </a>
</div>
gavgrif
  • 13,077
  • 2
  • 17
  • 22