spec关于计算CSS特异性的状态:(粗体)
Note: Repeated occurrences of the same simple selector are allowed and do increase specificity.
因此,例如
.class.class {}
的特异性是.class {}
的两倍-DEMO但是,对于术语“简单选择器” the spec来说,这是这样的:(粗体显示)
A simple selector is either a type selector or universal selector followed immediately by zero or more attribute selectors, ID selectors, or pseudo-classes, in any order.
因此,由于规范说允许重复出现相同的简单选择器-这意味着您也可以重复type selectors。
好吧,很显然,这样的事情将无法工作:
h1h1 { }
,所以我尝试了这个:
h1[]h1[] {}
-也不起作用,所以我想知道是否有办法做到这一点?
最佳答案
可以使用类型选择器来提高选择器的特异性,但传统上是不可以的。其原因在下面说明,但是对于那些只是在寻找替代方法的人,有两个。您可以在单个复合选择器中链接包含类型选择器的:not()
伪类:
h1 {} /* 1 type -> specificity = 0-0-1 */
h1:not(_) {} /* 2 types -> specificity = 0-0-2 */
h1:not(_):not(_) {} /* 3 types -> specificity = 0-0-3 */
h1:not(_):not(_):not(_) {} /* 4 types -> specificity = 0-0-4 */
或者,如果您需要支持不支持
:not()
的旧版浏览器,则可以在复杂的选择器的开头添加冗余类型选择器(例如html
和body
),尽管在这种情况下您可能会受限制得多,因为您可能无法考虑所有要素:h1 {} /* 1 type -> specificity = 0-0-1 */
body h1 {} /* 2 types -> specificity = 0-0-2 */
html body h1 {} /* 3 types -> specificity = 0-0-3 */
html body tr > td {} /* 4 types -> specificity = 0-0-4, assumes every td is a child of tr */
不用说,这些被认为是特异性黑客。与所有其他CSS hacks一样,请尽量使用它们(如果有的话)。
复合选择器在所有其他简单选择器之前最多只能具有一个类型选择器。从Selectors 3(将其称为简单选择器序列):
A sequence of simple selectors is a chain of simple selectors that are not separated by a combinator. It always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence.
和Selectors 4:
A compound selector is a sequence of simple selectors that are not separated by a combinator. If it contains a type selector or universal selector, that selector comes first in the sequence. Only one type selector or universal selector is allowed in the sequence.
仅类型选择器和通用选择器受此规则约束;您可以组合并重复其他简单的选择器以提高特异性。规范也许可以在有关计算特异性的部分中提醒读者这一点,但是我认为这不是绝对必要的。
从未明确说明此规则的原因,但可以很容易地推论出:
h1
。这与其他在语法中具有自己的区别符号的简单选择器不同,例如ID(#
),类(.
),伪类(:
)或属性选择器([]
)。您将无法拥有多个连续的类型选择器,而无法单独解析它们。 这是因为Selectors假定文档语言将每个元素定义为完全具有一种元素类型。例如,在HTML中,
h1
始终是h1
;它永远不能是任何其他类型的元素。要求元素既是h1
又是p
的复合选择器永远不会匹配任何内容,出于同样的原因,像[type=text][type=password]
之类的东西也永远不会匹配不支持重复属性的文档语言中的任何内容。 但是,考虑到以上几点,仍然可以通过使用
:not()
伪类来创建包含多个类型选择器以实现特异性的复合选择器::not()
伪类的特异性与其参数相同。伪类本身不计算在内。第一个链接中提到了这一点。这意味着:not(h1)
的特异性等同于h1
—一种类型选择器。 :not()
与任何其他类型选择器将得到保证的匹配。 _
。 关于css - 可以重复使用类型选择器来提高特异性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28299817/