Making two other div's change color when hover

2019-09-15 10:59发布

问题:

I have 3 div's. I would like to change some stuff in 2 of those div's when I hover over the "main"/"first" div. I am really, really trying to avoid any use of Javascript/jQuery, here.

I am pretty sure this can be done, I vaguely remember reading about it a while ago but I cannot find the link again and my previous searches have not helped, probably because I might not be using the correct terms.

Here's the code: HTML:

<div id=one></div>
<div id=two></div>
<div id=three></div>

CSS:

#one{background-color:blue;width:50px;height:50px;float:left;}
#two{background-color:green;width:50px;height:50px;float:left;}
#three{background-color:red;width:50px;height:50px;float:right;}

#one:hover > #two + #three { background-color: yellow; }

Can someone please help? How do I make the other two divs change color when I hover over the first one?

回答1:

DO you mean like this?

Fiddle

#one:hover ~ #two , 
#one:hover ~ #three  
{ background-color: yellow; }

Issue is that > mean it is immediate descendant selector and combination of selector with + won't work.



回答2:

You have 2 things to know.

First, you cant select 2 elements by id in one "rule", you need to use comma.

Second, > mean children of and + right next to of. So your rule mean :

#one
    #two //Children of #one
    #three //the selected one (children on #one)

Your rule should look like this :

#one:hover ~ #two, #one:hover ~ #three { background-color: yellow; }