34

From the CSS selector spec:

E + F matches any F element immediately preceded by a sibling element E.

What about operator precedence? What does #id1 #id2 + #id3 match? What about #id1 + #id2 #id3?

Is there a selector that means #id1 (#id2 + #id3) or (#id1 + #id2) #id3? (I'm assuming ( and ) aren't really allowed in CSS selectors, I'm not seeing them in the spec)

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • 1
    What would the difference be, between for example `#id1 (#id2 + #id3)` and `(#id1 #id2) + #id3`? – BoltClock Nov 15 '11 at 11:37
  • @BoltClock - true that, there isn't a difference. – ripper234 Nov 15 '11 at 12:13
  • 1
    @BoltClock on the other hand, given a (rather confusing) selector like `#id1 #id2 + #id3 #id4` the precedence *does* matter; the example given in this question might be bad, but the core of the question is still good. – Mark Amery May 22 '17 at 14:20
  • @Mark Amery: So it matters when you have no fewer than two descendant combinators. Yeah, that's a better example. – BoltClock May 22 '17 at 14:28

1 Answers1

47

Every sequence of simple selectors and combinators is read by browsers from right to left, in a linear fashion. Combinators do not affect the ordering in any way. The rightmost selector, after the last combinator if any, is known as the key selector (see the reference links below for more), and that identifies the element that the rule applies to (also known as the subject of the selector, although note that the key selector may not always represent the subject of the selector, since different applications implement selectors differently).

The selector #id1 #id2 + #id3 means

Select element #id3
if it directly follows as a sibling of #id2
that is a descendant of #id1.

A DOM structure in which #id3 would match the selector would look like this:

#id1
  ... any level of nesting
    #id2
    #id3

While #id1 + #id2 #id3 means

Select element #id3
if it is a descendant of #id2
that directly follows as a sibling of #id1.

And a DOM structure in which #id3 would match the selector would look like this:

#id1
#id2
  ... any level of nesting
    #id3

Notice the difference in the position of element #id2 in this DOM structure, as compared to the one above.

There isn't much of a precedence issue here since the descendant and sibling combinators go in different directions in the DOM. Both selector sequences read right to left either way.

Related answers:

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Now that I think about it, I believe even if parenthesis were allowed, then the expressions `#id1 (#id2 + #id3)` and `(#id1 #id2) + #id3` would be equivalent. Am I right? – ripper234 Nov 15 '11 at 11:49