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) { // Compare A-component if(x[0] !== y[0]) { return …


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!


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Comparing CSS Specificity Values." Bramus! | Sciencx - Tuesday January 25, 2022, https://www.scien.cx/2022/01/25/comparing-css-specificity-values-2/
HARVARD
Bramus! | Sciencx Tuesday January 25, 2022 » Comparing CSS Specificity Values., viewed ,<https://www.scien.cx/2022/01/25/comparing-css-specificity-values-2/>
VANCOUVER
Bramus! | Sciencx - » Comparing CSS Specificity Values. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/01/25/comparing-css-specificity-values-2/
CHICAGO
" » Comparing CSS Specificity Values." Bramus! | Sciencx - Accessed . https://www.scien.cx/2022/01/25/comparing-css-specificity-values-2/
IEEE
" » Comparing CSS Specificity Values." Bramus! | Sciencx [Online]. Available: https://www.scien.cx/2022/01/25/comparing-css-specificity-values-2/. [Accessed: ]
rf:citation
» Comparing CSS Specificity Values | Bramus! | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.