rss feed Twitter Page Facebook Page Github Page Stack Over Flow Page

What is Specificity in CSS

Once you've dived into CSS you come across the term specificity.

What do most CSS developers do when they first start out? They learn the ropes on how to code out CSS and use a good frame of mind when it comes to UI architecture. Because, let's all be honest, it never makes sense until you apply it. But what most don't realize is that you follow specificity guidelines without even knowing it. And this is the first battle to understanding one of the harder concepts to understand in css.

So what is specificity?

In simple terms, it's the weight of importance each selector/element carries when being applied. Did that make sense? Without all the very fancy terms, it's how css applies style and who does it listen to when applying style.

There are four rules to remember when determining the specificity of a selector:

Elements or Selectors Weight
HTML Elements = 1
Class and pseudo-classes = 10
ID Descriptos = 100
Inline Styling = 1000

Here are a few examples to better explain the concept.

Elements or Selectors Weight
div, ul, li 3 html elements is 1 + 1 + 1 = 0003
div, .myclass 1 html element, 1 class is 1 + 10 = 0011
.myclass, a:hover 1 class, 1 pseudo-class is 10 + 10 = 0020
#yourid, p, ul 1 id, 2 html element, is 100 + 1 + 1 = 0102
< div id ="myid" style="color: #fff" > style set inline, 1 id, is 1000 + 100 = 1100

Looking at the number weight each carries explains why when you set something inline it will always overwrite any id, class, or html tag set in the style sheet. Inline carries the highest weight of 1000.

When you set a global rule to a UL, and then you set a more specific rule to a class, the class overwrites it. Again the reason would be a class carries the weight of 10 while the UL element carries only a weight of 1.

If you were to give a < div > an id and a class and you happen to set a rule of color in both, the rule that would take precedence would be the id. Reason again lies in that the id has a weight of 100 and the class is only of 10.

So going back to my original comment of how we follow specificity, but we might not know it is simply saying if the rule of specificity was not met you would not be able to make sense of how your html elements are inheriting rules and why. As you learn to trouble shoot CSS, you slowly start to understand specificity and follow its guidelines.

This comes very handy when working in larger scale sites that have many developer hands in the pot. As a CSS developer you would need to understand how to trouble shoot the weight specifications in each rule and find the way to either overwrite the rule or find how to remove it.

So when someone throws to you the fancy term of "specificity", just answer them, "it's the base principle of style inheritance!" This tends to be a very popular interview question.

Happy CSSing!!!