Comparing CSS Specificity Values

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) { // x and y being arrays such as [1, 1, 2] that represent a specificity triple
  // Compare A-component
  if(x[0] !== y[0]) {
    return y[0] - x[0];
  }

  // Compare B-component
  if(x[1] !== y[1]) {
    return y[1] - x[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.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.