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:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With