为什么 CSS 逗号分隔的选择器在一个部分未知时会破坏整个规则?

Why do CSS comma separated selectors break entire rule when one part is unknown?

解释问题:

因此,如果您有一个看起来像这样的 CSS 规则:

h1, h1 a:hover {
  color: blue;
}

它工作正常,从可用性的角度来看,该示例可能不是最好的,但它确实有效。 (它可以证明问题...)

但是如果你加了逗号分隔(,)浏览器不理解,空洞规则会被忽略

 h1, h1 a:hover, h1:focus-within {
    color: blue;
 }

不理解 :focus-within 伪class的浏览器将忽略整个规则。这意味着即使是 h1 也不会获得指定的规则。


进一步想知道为什么会这样:

不要误会我的意思。忽略他们不知道的事情是 CSS!

的一个非常强大的功能

但为什么它没有设计成只忽略未知部分而所有其他选择器仍按预期工作的方式?

就我个人而言,我很少遇到这个问题,而且我已经接受了这样一个事实,即选择器中的一个错误会破坏整个规则。 但是很难解释为什么错误的声明或 属性 只会导致特定行被忽略,而选择器中的任何未知都会破坏整个块。

感觉好像遗漏了什么,所以如果有好的解释请告诉我,谢谢你这样做。


不满意的解决方案:

当然,解决方法是将选择器的 "dangerous" 部分分成新规则,如下所示:

h1, h1 a:hover {
    color: blue;
}
h1:focus-within {
    color: blue;
}

但这感觉很糟糕。 (由于"unnecessary"重复)

只是想把它放在这里。

事实证明这实际上是有意的并且在Selectors Level 3中定义(我强调):

If just one of these selectors were invalid, the entire group of selectors would be invalid. This would invalidate the rule for all three heading elements, whereas in the former case only one of the three individual heading rules would be invalidated.

Invalid CSS example:

h1 { font-family: sans-serif }
h2..foo { font-family: sans-serif }
h3 { font-family: sans-serif }

is not equivalent to:

h1, h2..foo, h3 { font-family: sans-serif }

because the above selector (h1, h2..foo, h3) is entirely invalid and the entire style rule is dropped. (When the selectors are not grouped, only the rule for h2..foo is dropped.)


CSS 2 没有指定当一个选择器错误时要做什么。事实上,W3C spec 表示压缩形式等同于写出的版本:

In this example, we condense three rules with identical declarations into one. Thus,

h1 { font-family: sans-serif }
h2 { font-family: sans-serif }
h3 { font-family: sans-serif }

is equivalent to:

h1, h2, h3 { font-family: sans-serif }

编辑:(谢谢@BoltClock):

CSS 2.1 确实指定了行为,它与 CSS3:

相同

(...) since the "&" is not a valid token in a CSS 2.1 selector, a CSS 2.1 user agent must ignore the whole second line.