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?

0

2 Answers 2

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/

4
  • Wow, that's so trivial I feel ashamed I couldn't think of it. Thanks.
    – Bobe
    Commented Sep 14, 2012 at 5: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
    Commented Sep 14, 2012 at 5:51
  • 1
    That's the catch, exactly. If you don't want that, JavaScript is the way to go.
    – joshnh
    Commented Sep 14, 2012 at 6:23
  • 1
    Life's never easy, is it? Well thanks for confirming my suspicions.
    – Bobe
    Commented Sep 14, 2012 at 6: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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.