Difference between CSS + selector and ~ selector

2019-01-28 10:24发布

问题:

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?

回答1:

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!



回答2:

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.



回答3:

The difference is the + will select the very next(adjacent) single element whereas ~ will select all preceded elements on the same level. But anyways you have the definition so I would like to contribute some simple real world scenario for better understanding.

div + p {
    color: red;
}

Demo Using +


div ~ p {
    color: red;
}

Demo 2 Using ~

So here, in the first example, it selects the p element which is adjacent to div but won't select the p which is later adjacent to the first p whereas if you use ~, it will select all the p elements which are followed by div element.