Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css -not selector- breaks precedence?

Tags:

html

css

In a css file, the last defined style takes precedence over previous defined ones.

But when using the not selector, the precedence gets broken and the class with the not selector gets precedence even though it's located at the top of the file.

What's the logic behind the precedence break?

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>

Result:

enter image description here

like image 967
AlikElzin-kilaka Avatar asked Dec 28 '15 08:12

AlikElzin-kilaka


1 Answers

You say:

In a css file, the last defined style takes precedence over previous defined ones

Not so fast... a class with higher specificity takes precedence over the order in which the classes appear in the CSS! (spec - Notice how 'specificity' appears before 'order of appearance' in the list)

So how would you calculate the specificity of the above classes?

From the w3c spec:

Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.

So the specificity of the selector .red-with-not:not(.something) =

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

Where

a = # ID selectors in the selector,

b = # class selectors, attributes selectors, and pseudo-classes in the selector and

c = # type selectors and pseudo-elements in the selector

As apposed to the other selectors .red and .blue - which have a specificity of only 010 (one class selector).


In case you're interested, specificity calculator is a good reference for calculating specificity.
like image 140
Danield Avatar answered Sep 19 '22 14:09

Danield