DEV Community

Cover image for How CSS Specificity WorksπŸ€ΉπŸΌβ€β™€οΈ
Sai gowtham
Sai gowtham

Posted on • Edited on

How CSS Specificity WorksπŸ€ΉπŸΌβ€β™€οΈ

We already know CSS stands for the cascading style sheets.

What the Cascading really mean is the browser first resolves the which stylesheet need to be applied to the HTML.Like we see blue color to the
links which come by the browser default.

Let's talk about the Specificity

Specificity is the weights applied to the CSS when we declared.

Weights really mean how we are applying a style to the particular HTML
element.

Like we are using id attributes to target the Html element or we used
class attributes sometimes we used direct element name like h1, p to apply
the styles.

Here the specificity comes in we are applying the styles using different selectors.
But browser applies styles to an element based on their weights.

In weights

  • First is inline CSS
  • Second id
  • Third class
  • Fourth Elements/Pseudo classes/Pseudo selectors

If We apply styles to the element with any selectors we have.If we just place an inline CSS it overrides the all styles which are before applied by using id, class, element.

(Important is never recommended)

If we add !important to the any of our selectors. Important overrides all of the other styles before we added to that element.

Check out in code pen I showed it clearly fork this pen and see the changes by removing important, inline CSS, id etc...

Find me on Twitter

Top comments (5)

Collapse
 
andrewlucker profile image
Andrew Lucker

Had to research this one. Specificity is a multi-digit ordinal with the four ranks you listed. For example: 0,1,0,4

smashingmagazine.com/2007/07/css-s...

Previously I thought it was a weighted floating point number, but that is wrong. Thanks for the clarification.

Collapse
 
sait profile image
Sai gowtham • Edited

Thanks for your comment πŸ€—πŸ€—

Collapse
 
dev_nope profile image
Vasile Stefirta πŸ‡²πŸ‡© ✈️ πŸ‡ΊπŸ‡Έ

This online Specificity Calculator is really handy specificity.keegan.st/ πŸ”₯

Collapse
 
sait profile image
Sai gowtham

Ss good tool

Collapse
 
shmidtelson profile image
shmidtelson

Guys, dont use !important tag.
Use if tomorrow armageddon