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

标签 css css-selectors css-parsing

<分区>

解释问题:

所以如果你有一个看起来像这样的 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.

关于css - 当一个部分未知时,为什么 CSS 逗号分隔选择器会破坏整个规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41246634/

相关文章:

performance - 你应该以什么顺序列出 CSS 属性以获得最快的速度?

javascript - 如何让同一类的两个 div 在屏幕上移动?

java - CSS 解析 : matching specific entities using cssparser

css - 如何将 "add details"转换为 CSS(例如框阴影)

javascript - 在 CSS 中使用一个 before 伪选择器来在一行中显示有关多个元素的信息

html - 在无法调整 HTML 的情况下,有没有办法隔离 HTML 内容进行样式设置?

javascript - jQuery - 错误 : unsupported pseudo: visible

html - 自定义 CSS 属性是否使用一个或两个前导破折号?

移除类时的 CSS 过渡

html - 在 bootstrap carousel 中的每个图像的底部添加链接