Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On a CSS hover event, can I change another div's styling? [duplicate]

Tags:

css

When I hover over a div or class with an id of "a", can I get the background color of a div or class with the id of "b" to change?

like image 796
Wesley Skeen Avatar asked Aug 02 '11 09:08

Wesley Skeen


People also ask

How do you hover with one element and affect another?

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.

How do you make something change color when you hover over it CSS?

Changing link color on hover using CSS To change the color of your link on hover, use the :hover pseudo property on the link's class and give it a different color.


1 Answers

Yes, you can do that, but only if #b is after #a in the HTML.

If #b comes immediately after #a: http://jsfiddle.net/u7tYE/

#a:hover + #b {     background: #ccc }  <div id="a">Div A</div> <div id="b">Div B</div> 

That's using the adjacent sibling combinator (+).

If there are other elements between #a and #b, you can use this: http://jsfiddle.net/u7tYE/1/

#a:hover ~ #b {     background: #ccc }  <div id="a">Div A</div> <div>random other elements</div> <div>random other elements</div> <div>random other elements</div> <div id="b">Div B</div> 

That's using the general sibling combinator (~).

Both + and ~ work in all modern browsers and IE7+

If #b is a descendant of #a, you can simply use #a:hover #b.

ALTERNATIVE: You can use pure CSS to do this by positioning the second element before the first. The first div is first in markup, but positioned to the right or below the second. It will work as if it were a previous sibling.

like image 126
thirtydot Avatar answered Nov 14 '22 05:11

thirtydot