Specificity

Specificity is one of the principles in CSS that is not easily understood.

To calculate how specific a rule is, each type of selector is assigned a numeric value. The specificity of a rule is then calculated by adding up the value of each of its selectors. Unfortunately, specificity is not calculated in base 10 but a high, unspecified, base number. This is to ensure that a highly specific selector, such as an ID selector, is never overridden by lots of less specific selectors, such as type selectors. However, if you have fewer than 10 selectors in a specific selector, you can calculate specificity in base 10 for simplicity’s sake.

The specificity of a selector is broken down into four constituent levels: a, b, c, and d. It can also be wtitten as 0,0,0,0

If the style is an inline style, then a = 1.

b = the total number of ID selectors.

c = the number of class, pseudo-class, and attribute selectors.

d = the number of type selectors and pseudo-element selectors.

Using these rules it is possible to calculate the specificity of any CSS selector. Table below shows a series of selectors, along with their associated specificity.

At first glance, all this talk of specificity and high but undefined based numbers may seem a little confusing, so here’s what you need to know. Essentially, a rule written in a style attribute will always be more specific than any other rule. A rule with an ID will be more specific than one without an ID, and a rule with a class selector will be more specific than

a rule with just type selectors. Finally, if two rules have the same specificity, the last one defined prevails.

Using specificity in your stylesheets

Specificity is very useful when writing CSS as it allows you to set general styles for common elements and then override them for more specific elements. For instance, say you want most of the forms on your site to be 30em wide but your search form needs to be only 15em wide:

form {width: 30em;}

form#search {width: 15em;}

Whenever you want to create a new form you do not have to worry about changing anything in the CSS, as you know it will be styled correctly. However, on larger sites you will find more and more exceptions will start to creep in. Maybe you will have a login form that you want to be 20em wide or a larger application form that needs to be 40em wide.

Each time you create a more specific style, you will probably need to override some of the general rules. This can lead to quite a bit of extra code. It can also start to get very complicated as one element may be picking up styles from a variety of places.