Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between CSS + selector and ~ selector [duplicate]

I saw a .class1 ~ .class2 selector today, and had to look it up.

div ~ p {}

Selects every <p> element that are preceded by a <div> element. In other words,

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

The <p></p> would be selected, right?

And then there's the + selector:

div + p {}

Selects all <p> elements that are placed immediately after <div> elements. In other words,

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

Am I right to think these are equivalent, or am I missing something?

like image 290
Michael Lewis Avatar asked Sep 19 '26 05:09

Michael Lewis


2 Answers

In your specific scenario, these two selectors are equivalent, however not in more general scenarios.

There is one important difference, the + combinator states:

The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence immediately precedes the element represented by the second one.

Imagine this scenario:

<div></div>
<p></p>      <!-- this will be selected with the + combinator -->

<p></p>      <!-- these two paragraphs will be affected by the ~ combinator -->
<p></p>      <!-- but NOT by the + combinator -->

And please don't confuse the W3C, a serious institution standardizing web technologies, with w3schools which is a rather bad source for information!

like image 60
Christoph Avatar answered Sep 20 '26 19:09

Christoph


From spec: Selectors Level 3

8.3.1. Adjacent sibling combinator (+)

The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence immediately precedes the element represented by the second one.

8.3.2. General sibling combinator (~)

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.

like image 42
MarcinJuraszek Avatar answered Sep 20 '26 21:09

MarcinJuraszek