Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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> 
like image 338
WilliamB Avatar asked Dec 30 '10 00:12

WilliamB


People also ask

How do I make hover affect another element?

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.

Can you hover a pseudo 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.

Why hover property is not working in CSS?

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.


2 Answers

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.

like image 152
stevelove Avatar answered Sep 20 '22 18:09

stevelove


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.

like image 26
Paul D. Waite Avatar answered Sep 19 '22 18:09

Paul D. Waite