css - Next-sibling 组合器不应该与复杂的选择器一起使用

标签 css css-selectors w3c

长话短说

根据规范,以下内容不应该起作用,但它确实起作用:

.a .b + .b {margin-top:20px;}

详情

According to the spec “Next-sibling combinator”(或“adjacent sibling combinator”)应该只适用于“简单选择器的序列”,which themselves are defined作为

... a chain of simple selectors that are not separated by a combinator.

在我上面给出的示例中,左侧的选择器 .a .b 包含一个“后代组合器”(由空格表示),因此不应被允许。

有趣的是,以下确实根本不起作用:

.b + .a .b {margin-top:20px;}

为什么我的介绍性示例适用于现代浏览器?

最佳答案

the specification你可以阅读:

The next-sibling combinator is made of the "plus sign" (U+002B, +) character that separates two sequences of simple selectors. 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.

没有人说它只适用于“简单选择器的序列”。它只是说 + 字符分隔两个简单选择器序列,除此之外它没有任何限制,因此您可以拥有更多选择器。

让我们考虑以下示例:

.a .b + .b
.b + .b
span.a:not(.b) .b + .b > div

在所有这些文件中,我们都有 .b + .b 部分,其描述为:

the "plus sign" (U+002B, +) character that separates two sequences of simple selectors.


如果您在规范的开头阅读,您会发现确认这一点的通用规则:

A selector is a chain of one or more sequences of simple selectors separated by combinators. One pseudo-element may be appended to the last sequence of simple selectors in a selector.

A sequence of simple selectors is a chain of simple selectors that are not separated by a combinator. It always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence.

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class.

基本上我们可以有

Seq_simple_selectors + Seq_simple_selectors Seq_simple_selectors > Seq_simple_selectors

然后在每个 Seq_simple_selectors 中我们可以有类似的东西:

 div.a.b#id::before

如果我们考虑您的示例 .a .b + .b,您有 3 个序列并且在每个序列中只有一个简单的选择器。

如果你有正确的 HTML,你的第二个例子也可以正常工作:

.b + .a .b {
  background: red;
  height: 20px;
}
<div class="b"></div>
<div class="a">
  <div class="b"></div>
</div>


无效的是像这样的.b + > .a。在这种情况下,我们没有:

the "plus sign" (U+002B, +) character that separates two sequences of simple selectors.

但是我们在一系列简单选择器和组合选择器之间有一个分离。

关于css - Next-sibling 组合器不应该与复杂的选择器一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58804827/

相关文章:

html - <button class ="button"> 标签 vs <div class ="button">

w3c - 什么是快速了解 MathML 及其在世界上的使用的最佳方式?

html - 如何使这种视差效果在移动浏览器上起作用?

javascript - 如何在模态内提交时隐藏表列

css - 在某个元素下重置和否决 CSS

python - 如何在 html 中单击 zebra datepicker 中的日期?

html - 现代浏览器关心 DOCTYPE 吗?

html - 防止滚动到填充区域

css - 第三级 CSS 下拉菜单不起作用

java - 单击与其他元素具有相同类名的元素