Change style of all other elements when one element is hovered
Asked Answered
C

2

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?

Caisson answered 14/9, 2012 at 5:37 Comment(0)
R
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/

Repository answered 14/9, 2012 at 5:42 Comment(4)
Wow, that's so trivial I feel ashamed I couldn't think of it. Thanks.Caisson
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.Caisson
That's the catch, exactly. If you don't want that, JavaScript is the way to go.Repository
Life's never easy, is it? Well thanks for confirming my suspicions.Caisson
V
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.

Vitric answered 12/1, 2014 at 23:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.