I have a structure of div
s inside div
s, something like:
<div>
<div>
<div class='a'>Hello</div>
<div class='a'>Stack</div>
<div>Overflow</div>
</div>
<div>
<div>You</div>
<div class='b'>Are</div>
<div class='b'>The Best</div>
</div>
<div>
<div>Have</div>
<div class='b'>a nice</div>
<div>Day !!</div>
</div>
</div>
I would like all div
s with class a
to change the background color when one of them is hovered by mouse. The same for all div
s with class b
: when one of div
s with class b
is hovered, all div
s with class b
should change the background color.
Is that possible to implement this behavior without Javascript ?
If the answer is no:
Is that possible if known that all div
s with class a
are consecutive div
s in the same level (i.e. siblings) ?
I can add also other classes to div
s, if needed.
You can get it "half working" in the simpler case where there are no container <div>
s:
<div>
<div class='a'>Hello</div>
<div class='a'>Stack</div>
<div>Overflow</div>
<div class='b'>Are</div>
<div class='b'>The Best</div>
<div>Have</div>
<div class='b'>a nice</div>
<div>Day !!</div>
</div>
Then you could use the general sibling combinator, with the unfortunate caveat that it only works for elements that come after the element described on the left-hand side. So, for example, if you hovered over the <div>
containing "The Best", only that and the "a nice" <div>
would have a changed background:
div.b:hover, div.b:hover ~ div.b {
background-color:#CCCCCC;
}
I wasn't able to come up with a way that would fully take care of your scenario through CSS alone, though. I'm leaning towards what the others have said about it not being possible (even in the simplified case) right now.
i can't think of any solution, except there are css-parent-selectors (and, as far as myself and google know, those don't exist). if there would be things like that, you could do something like selecting the top parent af the hovered element and then select all elements of your class within that top-element (would look like .a < parent < parent < parent .a{ /*styles*/ }
) - but, as said, this selectors don't exists, so the answer to you question is: no
No. Not without Javascript. CSS selectors are meant to apply styles to each element that matches the selector individually, so by design this won't happen.
Source
http://www.w3.org/TR/CSS2/selector.html#selector-syntax