Css Specificity

It often happens that the properties of an element are set by several different css selectors. For example, it could happen that the colour of a headline is generally set as black on all h1 elements (with the css h1 {color: black;}) while it at the same time is set as, say, green on headlines that have class="green" (with the css h1.green {color: green;}).

Css specificity is the prioritisation the browser does in order to decide, which css property that must prevail. Css specificity is only relevant when the same element has been declared by several selectors.

In the example of the green headline, it might feel obvious for most that it of course must become green. But in many scenarios it is not that obvious. It is therefore a necessity to know how the browser prioritises.

How to calculate specificity

Specificity can be calculated as a value. The selector with the highest value will prevail. If two properties happen to have the exact same specificity value, the one that appears last int he css code will prevail.

To calculate specificity, start at 0:

  • Add 1000 for the style attribute
  • Add 100 for each id
  • Add 10 for each attribute, class and pseudo-class
  • Add 1 for each element and pseudo-element

In an example like:

body #container .navigation a:visited {...}

the specificity will be:

100 (#container) + 10 (.navigation) + 10 (:visited) + 1 (body) + 1 (a) = 122

Specificity examples

* {...}0
span {...}1
span a {...}1+1 =2
a:hover {...}1+10 =11
span h1.green {...}1+1+10 =12
h1.green.large {...}1+10+10 =21
#container div h1.green {...}100+1+1+10 =112
<span style="...">1000


The !important selector is available in css to overwrite other selectors. Avoid it if possible, as it make the css code unstructured. It should never be necessary to use !important when the developer has full control of and access to the code. In other cases, it might be necessary to use !important, such as when working in systems where some preset css code must be overwritten.
en_GBEnglish (UK)