Comparing CSS Specificity

1 min read  •  27 June 2023
Views:

Specificity plays a important role in understanding CSS and how it gets applied. There can be cases where you've multiple selectors and you want to compare the specificity among them or maybe sort them with respect to their specificity.


There's an npm package and a UI playground to check that.


Let's take a very basic example and see how we can make use of it.


specificity-demo

So, in the above example we have the following basic markup and css.

<style>
  body > :first-child {
    background: red;
  }
  #first-element {
    background: green;
  }
  body > :first-child#first-element {
    background: blue;
  }
</style>

<body>
  <div
    id="first-element"
    style="width: 16rem; height: 16rem; border: 10px solid black;"
  ></div>
</body>

And, now if we want to compare these selectors to understand how it's getting applied, we can use the above mentioned playground. We can even sort the selectors within the playground.


specificity-playground-demo