DEV Community 👩‍💻👨‍💻

Cover image for Understanding CSS Specificity

Posted on

Understanding CSS Specificity

Have you ever had issues as to why the CSS rule wasn't being applied to your page? Well you might be facing issues with the CSS specificity or like how CSS computes which value is to be considered while the element is being rendered.

Let's first take a look at the definition of CSS specificity:

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.

Let's go more in detail about how the specificity is being calculated for each element that is being rendered, so following are the selectors through which we apply CSS to various elements:

  1. Inline-Styles
  2. IDs
  3. Classes, pseudo-classes, attribute
  4. Elements, pseudo-elements

Now using the above selectors we calculate that how specific is the value or the style that is being applied to the element.

You can write the above values as - (a,b,c,d)


a - inline-styles
b - ids
c - classes, pseudo-classes, attribute
d - elements, pseudo-elements

By default when the project is created all the above values are - (0,0,0,0)

Now keep in mind that the specificity decreases from left to right (i.e "a" being the most specific and "d" being the least)

Let us now understand this with an example:

Consider the following code which contains styles applied to the same element:

Consider this code pen for the example being discussed - Specificity Example


  color:orangered /*Specificity - (0,1,1,0)*/

#main-text{       /*Specificity - (0,1,0,0)*/

  color:red       /*Specificity - (0,0,0,1)*/

  color:green     /*Specificity - (0,0,1,0)*/
Enter fullscreen mode Exit fullscreen mode

We can see the above styles along with their specificity that is in the comment.

The element renders with the color "orangered" irrespective of it being written above all other statements, because on calculating the specificity we observe that both orangered and purple have an ID whereas other styles do not, so we may not consider them further.

Now on checking the next value we observe that for orangered we also have a class whereas for purple we do not and hence the specificity for orangered exceeds the one for purple.

Now keep in mind in case we have a 1000 classes and 1 Id for an element, then the rule written with that 1 Id will also dominate the one with even all 1000 classes combined.

The order of CSS statement will only matter in case two rules have the same value of Specificity

So that's how specificity of CSS works. Do play around with the values to gain a better understanding.

Top comments (0)

Tired of sifting through your feed?

You can change your feed and see more relevant posts by adding a rating to different tags on DEV. Head here to adjust your weights.