解释问题:
所以如果你有一个看起来像这样的 CSS 规则:
h1, h1 a:hover {
color: blue;
}
它工作正常,从可用性的 Angular 来看,该示例可能不是最好的,但它确实有效。 (它可以证明问题...)
但是如果你添加一个浏览器不理解的逗号分隔符(,),空洞规则将被忽略。
h1, h1 a:hover, h1:focus-within {
color: blue;
}
不理解 :focus-within 伪类的浏览器将忽略整个规则。这意味着即使是 h1 也不会获得指定的规则。
进一步想知道为什么会这样:
不要误会我的意思。忽略他们不知道的东西是 CSS 中一个非常强大的功能!
但为什么它的设计方式不是只忽略未知部分而所有其他选择器仍按预期工作?
我个人很少遇到这个问题,而且我已经接受了这样一个事实,即选择器中的一个错误会破坏整个规则。
但很难解释为什么错误的声明或属性只会导致特定行被忽略,而选择器中的任何未知内容都会破坏整个 block 。
感觉好像遗漏了一些东西,所以如果有好的解释请告诉我并感谢您这样做。
不满意的解决方案:
当然,解决方法是将选择器的“危险”部分分成新规则,如下所示:
h1, h1 a:hover {
color: blue;
}
h1:focus-within {
color: blue;
}
但这感觉很糟糕。 (由于“不必要的”重复)
只是想把它放在这里。
事实证明这实际上是有意的并且在 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.