return to my homepage
March 19th, 2011

CSS Specificity

From my experience, CSS Specificity is one of the hardest and most uncommonly used concepts of CSS. Understanding how CSS specificity works will dramatically reduce the time you spend bug hunting for cross browser styling errors.

What is CSS Specificity?
CSS Specificity is a type of weighting that has a bearing on how your cascading style sheet (CSS) rules are displayed. This weighting is calculated by the browser based on the CSS rules you have applied.

Understanding Weighting
The easiest way to learn the weights applied is to remember the rule below:

Start at 0.
Style attributes = 1000
ID's = 100
Attributes, class or pseudo-class = 10
Element name or pseudo-element = 1

So in this instance: body #wrapper .container img:hover would equal 122
100 for #wrapper, 10 for .container, 10 for :hover, 1 for body and 1 for img

Writing specific CSS saves you the heartache of wondering why the browser is not displaying specific style elements and also prevents you from using !important throughout your CSS.

If in the case that the weight values are equal, the last rule will be rendered.

Further Reading
There are many sites that cover this topic in greater detail. Below are just a few:

Cascade Inheritance: Specificity
CSS 2.1 Selectors Explained
CSS Specificity for Poker Players