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>
If you have two elements in your HTML and you want to :hover over one and target a style change in the other the two elements must be directly related--parents, children or siblings. This means that the two elements either must be one inside the other or must both be contained within the same larger element.
To clarify, you CAN NOT give :hover to a pseudo element. There's no such thing as ::after:hover in CSS as of 2018.
Some problems arise on small touch screen devices that do not support hover. Also, hover will not work if you use the wrong CSS format. Note that if you do not get the specificity right, the hover style will not work.
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.
There is the general sibling selector (~
) that selects sibling elements.
So with the HTML you’ve posted, #header:hover ~ .element
would select <div class="element">
when it’s a subsequent sibling of the hovered header.
Even IE 7 supports it, so you're on relatively solid ground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With