CSS Specificity and Exactness Explained

CSS is all about cascading or waterfall principle. You may know this principle, but still some ways CSS is constructed are obscure. So, let’s try to find out the specificity of CSS selectors that are abased on the struggle for dominance principle.CSS Specificity and Exactness to remember

First of all, we should interpret the concept of CSS specificity:

The exactness with which a vocabulary term covers a concept.

With many ways to target a single html element, CSS can do it through classes, pseudo-classes, ids, through CSS selectors, the html elements themselves or even inline. Thus, it really matters whether you target a div through its class instead of its id, because all the above mentioned ways carry a different weight of importance.

In other words, each selector carries a weight of its specificity and the sum of all these values is the computed weight for a selector. Here are some possible weights:

  • 1,0,0,0 : inline styles
  • 0,1,0,0 : ids
  • 0,0,1,0 : classes, pseudo-classes and attributes
  • 0,0,0,1 : elements and pseudo-elements
  • 0,0,0,0 : the * (universal selector)

Inherited properties and combinator (in the end of this list) carry no weight at all. Note that universal selector will still overwrite inherited properties.

Some elements can be targeted by several selectors carrying the same weight. In this case, the selector appearing last in the source will take preference. It is an important rule that can be abused when you deal with IE6.

Specificity Calculated

Note that the above mentioned calculations are not made in base-10. In other words, you are not able to get 11 classes to overwrite 1 id. Still the representation of the values with “,” can help to avoid some confusion. Just add all specificities within their respective weight category and compare results to other selectors. CSS Specificity and Exactness Explained for all

h1 (weight: 0,0,0,1 )
* h1 (weight: 0,0,0,1 )
.class #id #id2 p (weight: 0,2,1,1 )
#id2 #id p .class (weight: 0,2,1,1 )
.class.class2>*~p (weight: 0,0,2,1 )

Important Addendum to Consider

h1 {color:#c0c0c0 !important;}

Declaring something !important you fix that value as unchangeable. This declaration should be used with caution and only within user style sheets or a piece of code that can’t be overruled by others. So, try to avoid it.

Reference: www.onderhond.com/blog/work/css-specificity

Comments are closed.