Css -not selector-breaks priority?

In the css file, the last defined style takes precedence over the previously defined.

But when using not selector , priority is interrupted, and a class with not selector gets priority, even if it is at the top of the file.

What violates the priority logic?

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

+5
source share
2 answers

You speak:

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

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

So, how would you calculate the specifics of the above classes?

From w3c spec :

Selectors within the pseudo-class of negation are counted like any other, but negation itself is not considered a pseudo-class.

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

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

Where

a = # ID selector in the selector,

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

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

Like other .red and .blue , which have specificity of only 010 (one class selector).


If you are interested, a specificity calculator is a good reference for calculating specificity.
+4
source

The specifics for .red-with-not:not(.something) appear as "0020", and for .red or .blue - "0010". Therefore, priority is given to .red-with-not:not(.something) .

enter image description here

enter image description here

See CSS Specificity for more details.

+3
source

Source: https://habr.com/ru/post/1239338/


All Articles