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?
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With