0
#red, #blue {
    position: absolute;
    width: 100px;
    height: 100px;        
}
div:hover {
    background-color: yellow !important;
}
#red {
    background-color: red;
}
#blue {
    background-color: blue;
    top: 50px;
    left: 50px;
} 


<div id="red"></div>
<div id="blue"></div>

Is it possible to trigger hover event on multiple elements under cursor without using javascript? How can I make both squares yellow in this simple example?

svobol13
  • 1,842
  • 3
  • 25
  • 40

3 Answers3

4

Pretty little demo

Well all these answers are just SWELL so I'm throwing mine in just for kicks n giggles.

Wrap them into a blanket. Hover the blanket, you change both to yellow.

HTML

<div id="wrap">
    <div id="red"></div>
    <div id="blue"></div>
</div>

CSS

#red, #blue {
    position: absolute;
    width: 100px;
    height: 100px;
}
#red {
    background-color: red;
}
#blue {
    background-color: blue;
    top: 50px;
    left: 50px;
}
#wrap:hover > div {
    background-color: yellow !important;
}
Deryck
  • 7,608
  • 2
  • 24
  • 43
1

You can do like

#red:hover {
    background-color: yellow !important;
}

#red:hover + #blue {
    background-color: yellow !important;
}
#blue:hover + #red {
        background-color: yellow !important;
}

JSFiddle

#red:hover + #blue // triggers hover for another element
Praveen
  • 55,303
  • 33
  • 133
  • 164
  • I just answered similarly (I think you beat me by a hair), but I realized `#blue:hover + #red` won't work with the given markup, because blue doesn't come before red. Unfortunately, there's no pure-css fix for that. – Faust Jan 31 '14 at 06:51
  • @Faust You're right. I too missed it, thanks for pointing my mistake. – Praveen Jan 31 '14 at 07:28
0

Because you want to be able to select preceding elements, you cannot do this with CSS alone. CSS cascades down the tree, not up the tree. You can do this with JS though.

http://jsfiddle.net/x7cWq/1/

$('div').hover(function() {
    $('div').addClass('yellow');
});

$('div').mouseleave(function() {
    $('div').removeClass('yellow');
});

With CSS:

div:hover, 
.yellow {
    background-color: yellow !important;
}
Ming
  • 4,468
  • 1
  • 21
  • 21
  • Wow, mine's the only answer that actually works, and I get a downvote. I'm telling the truth: CSS **cannot** select a preceding element. OP asked if it was possible without JS: the answer is **no**. – Ming Jan 31 '14 at 06:47