Avoid Headaches by Understanding CSS Specificity

Written by ae-cordova | Published 2020/03/01
Tech Story Tags: css | css3 | css-selectors | web-dev | css-fundamentals | frontend | web-development | html

TLDR Specificity is a tricky one of the concepts you have to understand in CSS. If there are two or more CSS rules that point to the same element, the browser gives more weight to the one with the most specific selector. The browser will apply the style of the rule using the latter. The one appearing latest in the style-sheet wins in case of conflicting rules. If you have a rule you want to apply, no matter what, there is a keyword to override everything: "You override everything"via the TL;DR App

Among all the concepts you have to understand in CSS, Specificity is a tricky one; and, it may be the reason why that font-size is not being applied to the element you're trying to target. 
If you want to spend less time yelling at your DEV tools, you should understand how the browser reads your code and decides which styling to apply upon conflicting rules.
If there are two or more CSS rules that point to the same element, and changing the same property, the browser gives more weight to the one with the most specific selector. 
So, given the case, the universal selector * is less specific than an id selector #. The browser will apply the style of the rule using the latter.

Hierarchy, Specificity Value, and Calculation

Four (...well, I'd say 5) categories define the level of specificity and they hold different values:
*Note: I added a 5th one because it's a good idea to clarify that the Universal Selector and Inherited Style have value of 0
To calculate specificity you should add the values of each selector category and compare the total.  The highest value wins!
for example:

What if they have the same specificity?

The general rule is: the one closer to the HTML wins, but you can keep an eye on the following:
The latest. Upon conflicting rules, The one appearing latest in the style-sheet wins.
Position counts. If you have an external CSS style-sheet and also wrote CSS embedded in your HTML, in case of conflicts, the embedded one wins.

This is !important

If you have a rule you want to apply, no matter what, there is a keyword to override everything:
!important
Be careful and keep it as the last resource. It can make a mess out of your code if you over-use it.
Maybe that's why it's considered a bad practice.
You can read more about the correct and recommended usage in the MDN web docs.

More about the subject and references:

So, now you know!
...but, if you still want to read more about specificity, check out the following resources, which also happen to be my references for this story:
You can print these out to have as a QRC:
Happy coding!

Published by HackerNoon on 2020/03/01