Ky -
Ky -

Reputation: 32073

Why does does this CSS selector not work as I expected?

Why does the following code not color "Won" red? I would expect #sisters>*~#too to select all items who have an eventual sibling with #too (that is to say, all items before #too, i.e. #won). However, only #too is selected by #sisters>*~#too.

In short, Why does #sisters>*~#too not select its preceding sibling, #won?

<style>
#sisters>#too~*,
#sisters>*~#too {
    color: red;
}
</style>
<div id="sisters">
    <div id="won">Won</div>
    <div id="too">Too</div>
    <div id="tree">Tree</div>
    <div id="fore">Fore</div>
    <div id="jive">Jive</div>
</div>

SSCCE: http://jsfiddle.net/Supuhstar/XY4Dg/

Upvotes: 0

Views: 53

Answers (2)

DaniP
DaniP

Reputation: 38252

You can't select elements in ascendant way on CSS. You can be able to select just descendant and after elements. So with this selector:

#sisters>*~#too 

You are searching this way:

  • All elements with id too
    • That are siblings ~
      • Of any direct childrens >*
        • In a tag with id sisters

That way the CSS selectors always select the last item seted on the selector that meet all the previous conditions.

Upvotes: 4

coreyward
coreyward

Reputation: 80041

The tilde, known as the General Sibling Combinator, selects any sibling after the element matched on the left side of it. There isn't a way of selecting a preceding element with any selector available today in CSS, unfortunately.

Upvotes: 3

Related Questions