css - CSS+选择器和~选择器的区别

标签 css css-selectors

<分区>

我看到一个.class1 ~ .class2今天选择器,必须查找它。

div ~ p {}

选择每个 <p><div> 开头的元素元素。换句话说,

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

<p></p>会被选中,对吧?

然后是 +选择器:

div + p {}

选择所有 <p>紧跟在 <div> 之后的元素元素。换句话说,

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

我是否认为这些是等价的,还是我遗漏了什么?

最佳答案

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

有一个重要的区别,+ 组合符声明:

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.

想象一下这个场景:

<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 -->

请不要混淆 W3C ,一个严肃的标准化网络技术的机构,w3schools 是一个相当 bad source for information !

关于css - CSS+选择器和~选择器的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21264820/

相关文章:

javascript - 使用 jQuery 将带有 html 格式的文本附加到文本区域

javascript - 如何在 Plot 2 图表中以粗体显示轴标签

jQuery 索引和选择器 :lt and :gt

javascript - 隐藏特定表的第 n 个子级

html - CSS 替代 li :has(+ . class) 关系伪类和 li :not(. class ~ li)

css - 无法使第一个 <option> 不可见

javascript - 为什么这个网站在 IE8 下这么慢

html - 环形工艺微调器,在环周围具有渐变渐变效果

html - CSS 网格布局 - 如何将滚动条放在左侧,并从左到右填充

jquery - 选择末尾具有唯一编号的属性