This content originally appeared on Bram.us and was authored by Bramus!
In CSS, Specificity is expressed as a triad/triple (A,B,C)
. An example value would be (1,1,2)
. To compare specificity — i.e. to see which value has a higher specificity — you need to compare each component of the triple until you find a difference:
function compareSpecificity(x, y) {
// Compare A-component
if(x[0] !== y[0]) {
return y[0] - x[0];
}
// Compare B-component
if(x[1] !== y[1]) {
return y[1] - a[1];
}
// Compare C-component
if(x[2] !== y[2]) {
return y[2] - x[2];
}
// Equal!
return 0;
}
To more easily sort Specificity triads, Kilian looked for something else:
The goal is to end up with a single number for each specificity that we can then compare and sort with.
Now, it’s not as simple as adding up each component of the triad, because a B
-value of 10
does not beat an A
-value of 1
. Instead, you’ll need to pad the numbers.
Comparing CSS Specificity Values →
💡 This is the exact same approach PHP does internally for its PHP_VERSION_ID
constant. PHP 5.2.7 for example, gets a value of 50207
.
This content originally appeared on Bram.us and was authored by Bramus!
Bramus! | Sciencx (2022-01-25T15:13:00+00:00) Comparing CSS Specificity Values. Retrieved from https://www.scien.cx/2022/01/25/comparing-css-specificity-values-2/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.