Avoid Headaches by Understanding CSS Specificity  by@ae-cordova

Avoid Headaches by Understanding CSS Specificity

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"
image
Angel Cordova HackerNoon profile picture

Angel Cordova

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. 

image

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:

image

*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:

image

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.

image

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.

image

This is !important

If you have a rule you want to apply, no matter what, there is a keyword to override everything:

!important

image

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!

react to story with heart
react to story with light
react to story with boat
react to story with money
L O A D I N G
. . . comments & more!