DEV Community

Cover image for Importance of CSS Specificity
Faisal Jawed Khan
Faisal Jawed Khan

Posted on

Importance of CSS Specificity

CSS specificity is an important topic if you want to get better at CSS. If you give the same element two or more CSS rules, then which style declaration will be applied to that HTML element?

Here comes an important concept called CSS Specificity, here the listed selector categories are in the order of decreasing specificity.

Important > inline styles > ID > class, pseudo-class, attributes > Elements

According to MDN, the browser will decide which CSS property values are more relevant to that element and will be applied. Simply if two or more CSS selectors apply to the same then which has the highest specificity will be applied to that element.

These selector categories are represented: 0 - 0 - 0 - 0 - 0 in that order.

Let us take one example:

<button class=”class-btn” id=”id-btn”> Hello World! </button>

  1. !important: This property overrides all others. style: 1 - 0 - 0 - 0 - 0

button {
color: “red” !important;
}

  1. Inline Styles: if an element has an inline style then 0 - 1 - 0 - 0 - 0

<button style=”color: blue”>Hello World!</button>

  1. ID Selector: if the element has an ID selector then 0 - 0 - 1 - 0 - 0

#id-btn {
color : “blue”;
}

  1. If the element has a class, pseudo-class or attribute selector then add 1: 0 - 0 - 0 - 1 - 0

.class-btn {
color : “violet”;
}

  1. Add 1 to the element selection: 0 - 0 - 0 - 0 - 1

button {
background : “yellow”;
}

Now I have one question for you to better understand this concept.

Importance of css specificity

What would be the color of the heading “Hello World!”?

A. Red
B. Green
C. Violet
D. Yellow

Now If you are confused then let’s understand the question

h3.heading {
color: green;
}

Specificity is 0 - 0 - 0 - 1 - 1, because it has 1 class and 1 element.

.main h3 {
color: violet;
}

Specificity is 0 - 0 - 0 - 1 - 1, because it has 1 class and 1 element.

.heading {
color: red;
}

Specificity is 0 - 0 - 0 - 1 - 0, because it has only 1 class.

h3 {
color: yellow;
}

Specificity is 0 - 0 - 0 - 0 - 1, because it has only 1 element.

So now color green and violet have same specificity that is 0 - 0 - 0 - 1 - 1.

Now according to cascading style sheet rule, whichever rule is applied the latest that is found in the bottom most will be the one that is applied. So in our question the violet color is the applied in the bottom most.

So the answer is Violet.

Conclusion

I hope you understand the concept of CSS Specificity and if you like the blog and If you think this will be helpful for you do Like, Comment, and Share with your colleagues and friends.

Do Follow me here on dev.to

Until then Happy Coding.

Top comments (0)