且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CSS +选择器和〜选择器之间的区别

更新时间:2022-12-22 16:30:31

在您的特定场景中,这两个选择器是等效的,但不是更一般的情况。



有一个重要的区别, + 组合器状态:


由两个序列表示的元素在文档树中的
***享相同的父元素,并且由第一序列
立即表示的元素在由第二序列表示的元素之前。

想想这种情况:
 < div&gt ;< / div> 
< p>< / p> <! - 这将使用+组合器 - >

< p>< / p> <! - 这两个段落将受到〜组合器 - >
< p>< / p> <! - but NOT by the + combinator - >

请不要混淆 W3C ,一个严肃的机构,标准化网络技术,使用w3schools这是一个相当坏的信息来源


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!