SN Blog

Understand CSS Specificity

☕ 4 min read 330

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; }

Classes, attributes and pseudo selectors

They all have weight of 10 for each donated element.

.headline { color: #f1f1f1; }

Elements

Elements have weight of 1.

h1 { color: #f1f1f1; }

Exceptions

There are also some exceptions to these rules and we will analyze them in this section.\n

The universal selectors (*, +, -, >, ~) have value of 0.

The !important value overrides absolutely everything and has value of 10000, but we should avoid using it , just in case.

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; }
ul#ul > li:hover { color: green; }
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!

0 Comments

Add a comment