css - 计算 :not() pseudo-class 的 CSS 选择器特异性

标签 css css-selectors pseudo-class css-specificity

我已经知道如何计算 CSS 的选择器特异性(规范中提到的 a/b/c/d)。但是,我无法确定如何为 :not() 伪类计算它。请参阅以下示例:

input:not([type="text"],[type="password"],.someClass) {...}
input:not(#someId[type="text"]) {...}

假设它们都适用于一个元素,这两个是否应该计算为(0011),因此它们应该按照出现的顺序排序?或者是否应该进一步单独计算 :not() 伪类中的选择器,这取决于哪个匹配,作为确定优先于另一个的第二步?

最佳答案

Assuming both of them apply to one element, should these two be calculated as (0011) and therefore they should be ordered according to order of appearance? Or should the selectors inside the :not() pseudo-class be further calculated separately depending on which one match as a second step to determine the one that have precedence over the other?

如果您正在实现 Selectors 3 , 根本不应该计算它们。如前所述,根据该规范,您的两个选择器都是无效的,因为它只定义 :not() 一次接受一个简单的选择器。

如果您将它们展开以验证它们(按照给定的说明/示例 here ),那么它们的特异性将计算如下:

/* 2 attributes, 1 class, 1 type -> specificity = 0-3-1 */
input:not([type="text"]):not([type="password"]):not(.someClass)

/* 
 * 1 ID, 1 type        -> specificity = 1-0-1
 * 1 attribute, 1 type -> specificity = 0-1-1
 */
input:not(#someId), input:not([type="text"])

因为 Selectors 3 says :

Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.

此外,针对您的评论:

True, according to specs, simple selectors only. But some browsers support multiple ones. Some of them don't, and some dropped them later. Also, you can write the same rule even with simple selectors like this instead: input:not([type="text"]):not([type="password"]):not(.someClass) which is better and work as well. Does this mean it should be calculated as 0031, then? How about those that support multiple ones, how do they calculate?

我所知道的唯一 浏览器在 :not() 中支持多个选择器是 Firefox 3.0,它这样做是因为一个错误。选择器 3 从不 允许 :not() 包含多个选择器——这仅在 Selectors 4 中引入,甚至还没有明确定义特异性计算1,所以即使您尝试实现选择器 4(我严重怀疑您是),您会被卡住。

我不清楚 Firefox 3.0 是如何通过其版本的 :not() 选择器实现特异性的,我没有它的副本来测试,但我认为可以安全地假设它不再重要,因为它从来都不是预期的行为。 好的,所以我选择了 Firefox 3.0 beta 1、3.0.0、3.0.18 和 3.1 beta 1,但都没有完全重现此行为。好了。


1 请注意,当前的 2013 ED 和 2011 FPWD 都一致表示 :not() 的特异性等于它的特异性最具体的论点,但这在未来可能会改变。

关于css - 计算 :not() pseudo-class 的 CSS 选择器特异性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15879843/

相关文章:

css - 无法在 Selenium 中使用 CSS 选择器选择同级

html - 伪选择 nth-child tweeking

html - 当所有 child 都相同时应用样式

html - 如何更改 Bootstrap 模式的边界半径?

HTML5/CSS3 Circle inside a circle with inner circle stick on top inside the outer circle

html - 盒子阴影副作用模糊不平滑。阴影中的内部正方形

html - 如何在 Angular2 (ngx) 中通过 css 选择器找到元素?

css 将样式应用于除最后一行之外的所有元素

html - "pseudo"在 CSS 中是什么意思?

css - 将 CSS 应用于 Crystal 报表