jos*_*unt 6 css css-selectors css-specificity
例如,为标准输入样式,我写了类似的东西:
input:not([type="checkbox"]):not([type="radio"]) {
background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)
然而,这会增加特异性,所以如果我想使用类来覆盖它,我必须做类似的事情:
.red.red.red {
background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在不改变功能的情况下降低原始输入选择器的特异性?
不幸的是,在 Selectors 3 中,这是您能做的最好的事情,因为:not()
只接受一个简单的选择器。话虽如此,您的重写规则中的选择器可以替换为input.red.red
\xe2\x80\x94 您不需要比属性选择器更多的类选择器,除非该规则必须出现在样式表中的较早位置。
这是 Selectors 4 通过增强:not()
特异性来解决的另一个问题。在 Selectors 4 中,您将能够仅用一个:not()
伪值替换所有这些否定,从而有效地将原始选择器中的特异性降低为仅一个属性选择器。来自第 16 节:
\n\n\n:not() 伪类的特异性被其选择器列表参数中最具体的复杂选择器的特异性所取代。
\n
由于任何属性选择器都同样特定于类选择器,因此列表中任意数量的单独属性选择器的特殊性永远不会超过其中一个的特殊性。这使您可以只使用一个类选择器进行覆盖,而不必重复它。
\n\n以下内容在 Safari 中作为概念验证工作:
\n\n/* 1 type, 2 attributes -> specificity = (0, 2, 1)\r\ninput:not([type="checkbox"]):not([type="radio"]),\r\n 1 type, 1 attribute -> specificity = (0, 1, 1) */\r\ninput:not([type="checkbox"], [type="radio"]) {\r\n background-color: blue;\r\n}\r\n\r\n/* 1 type, 1 class -> specificity = (0, 1, 1) */\r\ninput.red {\r\n background-color: red;\r\n}
Run Code Online (Sandbox Code Playgroud)\r\n<input type="checkbox">\r\n<input type="radio">\r\n<input type="text">\r\n<input class="red" type="text">
Run Code Online (Sandbox Code Playgroud)\r\n