在css文件中,最后定义的样式优先于先前定义的样式.
但是当使用时not selector,优先级会被破坏,并且具有not selector优先级的类即使它位于文件的顶部也是如此.
优先权突破背后的逻辑是什么?
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<style>
.red-with-not:not(.something) {
background: red;
}
.red {
background: red;
}
.blue {
background: blue;
}
</style>
</head>
<body class="base">
<h1 class="blue red-with-not">Expected Blue - PROBLEM</h1>
<h1 class="blue red">Expected Blue - Great!</h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
结果:
你说:
在 css 文件中,最后定义的样式优先于以前定义的样式
没那么快……具有更高特异性的类优先于类在 CSS 中出现的顺序!(规范- 请注意列表中“特殊性”如何出现在“出现顺序”之前)
那么如何计算上述类别的特异性呢?
从w3c 规范:
否定伪类中的选择器与其他选择器一样被计算在内,但否定本身并不算作伪类。
所以选择器的特殊性.red-with-not:not(.something)=
/* a=0 b=2 c=0 -> specificity = 020 (two class selectors) */
Run Code Online (Sandbox Code Playgroud)
在哪里
a = # 选择器中的 ID 选择器,
b = # 选择器中的类选择器、属性选择器和伪类
c = # 类型选择器和选择器中的伪元素
与其他选择器.red和.blue- 只有 010(一类选择器)的特异性相同。