Can you apply a CSS hover effect to an element that’s not a child of the hovered element?

WilliamB picture WilliamB · Dec 30, 2010 · Viewed 34.1k times · Source

I was not sure if this is possible or not. I am working in CSS3 animations right now and I need to hover on a link that will effect other div element(non-child) on the page. I was not sure if there is a work around or not.

<style type="text/css">

#header {
 background-color:red;
}

#header:hover .element {
 background-color:blue;
}

.element {
 background-color:green;
}

</style>

-

<header id="header">
     <li><a href="#">Hover</a></li>
</header>

<div class="element" >
 <p>hello world </p>
</div>

Answer

stevelove picture stevelove · Dec 30, 2010

Since these are adjacent siblings, you can use the adjacent sibling selector: +.

#header:hover + .element {
 background-color:blue;
}

This is well supported in most modern browsers*. IE7 can be buggy. IE6 and below does not support it.

* One of the other answers mentions the general sibling selector, which does not work in Webkit when used with a dynamic pseudo-class like :hover due to this bug. Take note that this same bug will cause problems in Webkit if you attempt to stack adjacent sibling selectors with a dynamic pseudo-class. For example, #this:hover + sibling + sibling will not work in Webkit.