css -not选择器 - 打破优先权?

时间:2015-12-28 08:39:52

标签: html css css3

在css文件中,最后定义的样式优先于先前定义的样式。

但是当使用not selector时,优先级会被破坏,而not selector的类会获得优先权,即使它位于文件的顶部。

优先权突破背后的逻辑是什么?

Example:

<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>

结果:

enter image description here

2 个答案:

答案 0 :(得分:4)

你说:

  

在css文件中,最后定义的样式优先于以前的样式   定义的

不是那么快......具有更高特异性的类优先于类在CSS中出现的顺序! (spec - 请注意'特异性'如何在列表中'出现顺序之前出现

那么你如何计算上述类的特异性?

来自w3c spec

  

否定伪类中的选择器与其他选择器一样,   但否定本身并不算作伪阶级。

因此选择器.red-with-not:not(.something) =

的特异性
/* a=0 b=2 c=0 -> specificity = 020 (two class selectors) */

哪里

a =选择器中的#ID选择器,

b =选择器中的#class选择器,属性选择器和伪类

c =选择器中的#type选择器和伪元素

与其他选择器.red.blue相关 - 它们的特异性仅为010(一个类选择器)。

<小时/>  如果您感兴趣,specificity calculator是计算特异性的良好参考。

答案 1 :(得分:3)

.red-with-not:not(.something)的特异性出现在&#39; 0020&#39;而对于.red.blue,则出现在&#39; 0010&#39;。因此,优先考虑.red-with-not:not(.something)

enter image description here

enter image description here

请参阅Specifics on CSS Specificity以获取更多理解。