2

For instance, div > p can be used to select all <p> elements that are direct children of a <div> element. Is it valid to use div > p > span to select a <span> elements that has a <p> parent and a <div> grandparent?

What about other operators in CSS selectors? Is it valid to use '+' in div + p + span or ',' in div, p, span?

How about combining different selectors? Like div + p > span?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
CrepuscularV
  • 983
  • 3
  • 12
  • 25

1 Answers1

5

Note that Selectors doesn't use the term "operator". The > and + symbols are more accurately known as combinators, while the comma is merely a symbol used to group selectors into a list, and doesn't belong in the same category as the > and + combinators.

As of Selectors level 4, combinators define a relationship between two elements, so they are indeed binary. And you can indeed use > or + multiple times in succession to refer to grandparents or other adjacent siblings. For example, div > p > span represents the following HTML fragment:

<div>
  <p>
    <span></span>
  </p>
</div>

And div + p + span represents the following fragment:

<div></div>
<p></p>
<span></span>

You can also mix and match combinators to represent even more complex structures. For example, div + p > span represents a <span> whose parent is a <p> which in turn directly follows a <div>, as given by the following fragment:

<div></div>
<p>
  <span></span>
</p>

Switching the combinators around, div > p + span represents a <span> that directly follows a <p> which in turn is a child of a <div>:

<div>
  <p></p>
  <span></span>
</div>

Notice how this implies that both the <span> and the <p> are children of the same <div>.

Keep in mind though that every complex selector targets the rightmost element (known as the subject of the selector). Unfortunately, this coupled with combinators being binary means that not all structures can be represented. See my answer to this question for an extremely in-depth explanation of both of these concepts and why such a limitation arises as a result.


You can also use , multiple times to group as many selectors together as you like, but again this is separate from the notion of combinators. The difference is that combinators link elements together to form a complex selector representing a singular cohesive structure, whereas the comma groups multiple complex selectors into a single CSS rule for the sake of convenience.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356