General sibling selectors, this is what the tilde expresses, will only select the siblings following (not preceeding) the matched element.
The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.
Reference: http://www.w3.org/TR/css3-selectors/#general-sibling-combinators
In your case there might be a CSS-only chance to archive this. Actually two ...
Chance 1
On parents :hover
, change the children.
#container:hover div:first-child {
background-color: #cff;
}
In your case, this required #container
to be display: inline-block;
, otherwise the red box would change too, when hovering the empty area right to both boxes.
Bin: http://jsbin.com/dilitucije/1
Works in all modern browsers and most older browsers too.
Chance 2
I'd use flexbox with defined order to reverse the rendering of both items. Since the rendering order of elements is reversed but the DOM order is not, this works.
CSS:
.reversed {
display: flex;
flex-direction: column-reverse; /* reverse rendering */
}
#container div:hover:first-child ~ div {
background-color: #cff;
}
Explanation of the Flexbox rules:
- use Flexbox (great explanation, W3C spec)
- order the items in rows (the container is a "
column
"), reverse the order of the items within the .reversed
container (first DOM node is rendered last, last DOM node is rendered first)
Add the class to your #container
<div id="container" class="reversed">...</div>
Bin: http://jsbin.com/piyokulehe/1
Works in FF 34, Chrome 39, should work in at least IE 11 too (probably not IE10).
Update:
- Fixed wrong
row-reverse
(the example uses column-reverse
, matches your requirement)
- Removed unnecessary
justify-content
(since the items are rendered into rows, this is not necessary)
- Added explanaition to the Flexbox solution