【问题标题】:CSS specificity not working as expected in ChromeCSS 特异性在 Chrome 中无法按预期工作
【发布时间】:2014-03-01 21:45:26
【问题描述】:

在阅读6.4.3 Calculating a selector's specificity之后,我预期会发生的事情和实际发生的事情似乎是矛盾的。很明显,我理解错了。如果有人可以简要解释一下为什么我在这 1 点上错了以及如何解决它,那就太好了。

/* opt.css */
#opt input[type="text"] { width: 200px; }
#tok { width: 300px; }

/* opt.html */
<div id="opt"><input id="tok" type="text" /></div>

我期待,因为#tok#opt input[type="text"]具体,输入框的宽度将是 300 像素,但它是 200 像素。

#opt input[type="text"]  /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */
#tok                     /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */

我可以通过 Chrome Inspector 看到 200px 获得了优先级,而 300 被划掉了,所以我对特异性的理解是错误的。我只是不明白我怎么弄错了。 b 不会覆盖cd

还有如何解决这个问题。

感谢您的帮助。

【问题讨论】:

    标签: css google-chrome google-chrome-extension css-selectors


    【解决方案1】:

    #tok 不如#opt input[type="text"] 具体:

    #tok                     /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */
    #opt input[type="text"]  /* a=0 b=1 c=0 d=1 -> specificity = 0,1,0,1 */
    

    b = id 的数量
    c = 属性和伪类的数量
    d = 元素名称和伪元素的数量

    【讨论】:

    • 但是#opt 是#tok 的父级,而不是#tok,所以该部分肯定不会只应用输入[type="text"]??
    • 是的,但是正如您在上面看到的,两个选择器中的 id 数量相同,但是由于您在 #opt input 中也使用了元素选择器,因此它比 #tok 更具体,因此该规则优先
    • 对于问题的第二部分,我该如何解决?
    • 只需使用#opt #tok {width:300px},因为它有两个ID,#opt input 会更具体
    • 谢谢您,我已经阅读了此内容并按照您的方式进行了解释。我只是认为'Direct ID'和'any ID'之间应该有区别。因为#tok是我要使用的实际项目的ID,而#opt只是父项的ID。不过,它不像我将能够改变 w3c 的标准..
    猜你喜欢
    • 2015-03-04
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2017-04-17
    • 2022-08-15
    • 2015-06-25
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多