DEV Community

Cover image for Understand CSS Specificity
Svetloslav Novoselski
Svetloslav Novoselski

Posted on

Understand CSS Specificity

CSS Specificity is the set of rules that decide what styles are applied to elements, the more specific it is, the more weight it has in determining the style of an element.

Why do I need to know that?

You may ask yourself why do I need to understand CSS Specificity, may I just write !important when some styles are not applied.
The answer is NO! By understanding how styles are applied, your code become more clean and easy to read. It is easier to change a particular style if you know exactly which selector to modify and you will no dig into naming architecture and ensuring that selectors won't conflict to each other.

Which selector has bigger weight?

There is a system with four categories which give to each selector weight, the most specific selector that bigger weight it has.
Four Category System CSS Specificity

Style Attribute

Inline Style overrides all other styles and has weight 1000

ID Selectors

IDs has weight 100

#headline {
    color: #f1f1f1; 
}
Enter fullscreen mode Exit fullscreen mode

Classes, attributes and pseudo selectors

They all have weight of 10 for each donated element.

.headline {
    color: #f1f1f1; 
}
Enter fullscreen mode Exit fullscreen mode

Elements

Elements have weight of 1.

h1 {
    color: #f1f1f1; 
}
Enter fullscreen mode Exit fullscreen mode

Exceptions

  1. There are also some exceptions to these rules and we will analyze them in this section.
  2. The universal selectors (*, +, -, >, ~) have value of 0.
  3. The !important value overrides absolutely everything and has value of 10000, but we should avoid using it , just in case.
  4. The pseudo-class :not() has no specificity either. ## Example Let's get these two selectors and see which one will be applied.
ul.ul > li:nth-child(2):hover {
    color: blue;
}
Enter fullscreen mode Exit fullscreen mode
ul#ul > li:hover {
   color: green;
}
Enter fullscreen mode Exit fullscreen mode

The second selector is more specific and has bigger weight, so it's style will be applied.
The weight of the first one is 32 and the second is 112.

What we have learned?

All css selectors have weight, the more specific it is, the more weight it has. Avoid using !important. Always look a way to use specificity before considering !important.

📩 If you like this post, subscribe and comment what other topics should I write about!

Latest comments (0)