CSS Specificity

CSS Specificity Wars

Writing CSS code up to latest standards might sound easy for many web developers but yet only few understand CSS in depth and are able to write good reusable CSS.

One of the things to take into account when writing CSS code, it’s the concept of CSS specificity.

As Mozilla Developer Network defines it, specificity is nonetheless:

Specificity is the means by which a browser decides which property values are the most relevant to an element and gets to be applied. Specificity is only based on the matching rules which are composed of selectors of different sorts.

Crescent order of specificity

The following list of selectors is by increasing specificity:

  • Universal selectors
  • Type selectors
  • Class selectors
  • Attributes selectors
  • Pseudo-classes
  • ID selectors
  • Inline style

As you can see from the picture on top, CSS Specificity can be represented by 4 columns of priority:





Left to right, the highest number takes priority.

Therefore never use inline styles for CSS because they have the highest priority in the specificity stack. Furthermore, using inline styles would go against the principle of keeping separated each web technology in order to improve code reusability and have a modular approach:

HTML for structure

CSS for presentation

JS for behaviour

Also, avoid using IDs for CSS but instead use classes which can be much more reusable in your web project.




Useful resources

CSSwizardy.com   http://csswizardry.com/2014/07/hacks-for-dealing-with-specificity/

Mozilla Developer Network   https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

Smashing Magazine  http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/

CSS Specificity Wars  http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html

Posted in css

Leave a Reply

Your email address will not be published. Required fields are marked *