9

Let's say I have a bunch of divs at the same DOM level. When I hover over one, I want all the others to change style (ie. reduce opacity or change background), while the one that is hovered stay the same.

I can't use the + or ~ selectors, because I need it to select all siblings, not just the directly adjacent one or only the following siblings. Basically what I'm looking for is an "all siblings but this one" selector. Does this exist? Is there a way to achieve this without JavaScript?

Bobe
  • 2,040
  • 8
  • 29
  • 49

2 Answers2

16

The trick is to place the hover pseudo-selector on the parent element, and then style the child accordingly. Here is what I'm referring to:

.parent:hover .child {
    opacity: .5;
}
.parent .child:hover {
    opacity: 1;
}

Here is a demo: http://jsfiddle.net/joshnh/FJAYk/

joshnh
  • 8,374
  • 4
  • 35
  • 53
  • Wow, that's so trivial I feel ashamed I couldn't think of it. Thanks. – Bobe Sep 14 '12 at 05:50
  • 1
    But wait, there's a catch. There is a lot of empty space between these divs I mentioned and I don't want them dimming just by having the cursor in the parent div. – Bobe Sep 14 '12 at 05:51
  • 1
    That's the catch, exactly. If you don't want that, JavaScript is the way to go. – joshnh Sep 14 '12 at 06:23
  • 1
    Life's never easy, is it? Well thanks for confirming my suspicions. – Bobe Sep 14 '12 at 06:49
2

The example above is very good, but if there is margin between divs and you don't want the effect to trigger when hovering over the empty space, there's no need for javascript.

Here's a simple workaround:

just add float:left to .child and be sure that .parent has overflow:visible (it should be visible by default).

By doing this, .parent becomes 0px high (so empty space won't trigger the effect) but hovering over .child triggers both :hover pseudoclasses.

Wilq
  • 2,245
  • 4
  • 33
  • 37
mtt
  • 21
  • 2