CSS Specificity

CSS Specificity is the set of the rules applied to CSS selectors in order to determine which style is applied to an element. The more specific a CSS style is, the higher point value it accrues, and the likelier it is to be present on the element’s style.

CSS Specificity-Calculation

Specificity is a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector. When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element. Specificity only applies when the same element is targeted by multiple declarations. As per CSS rules, directly targeted elements will always take precedence over rules which an element inherits from its ancestor.

Start at 0, add 1000 for style attribute, add 100 for each ID, add 10 for each attribute, class or pseudo-class, add 1 for each element name or pseudo-element.

Consider these three code fragments:

Example

A: h1
B: #content h1
C: <div id=”content”><h1 style=”color: #ffffff”>Heading</h1></div>

The specificity of A is 1 (one element)
The specificity of B is 101 (one ID reference and one element)
The specificity of C is 1000 (inline styling)

Since 1 < 101 < 1000, the third rule (C) has a greater level of specificity, and therefore will be applied.

CSS Specificity-Rules

  • Always look for a way to use specificity before even considering !important
  • Only use !important on page-specific CSS that overrides foreign CSS (from external libraries, like Bootstrap or normalize.css).
  • Never use !important when you’re writing a plugin/mashup.
  • Never use !important on site-wide CSS.

CSS Specificity-important

  • The universal selector (*) has no specificity value (0,0,0,0)
  • Pseudo-elements (e.g. :first-line) get 0,0,0,1 unlike their pseudo-class brethren which get 0,0,1,0
  • The pseudo-class :not() adds no specificity by itself, only what’s inside it’s parentheses.
  • The !important value appended a CSS property value is an automatic win. It overrides even inline styles from the markup. The only way an !important value can be overridden is with another !important rule declared later in the CSS and with equal or great specificity value otherwise. You could think of it as adding 1,0,0,0,0 to the specificity value.

CSS Specificity-example

div#a {background-color: red;}
#a {background-color: green;}
div[id=a] {background-color: yellow;}
.intro {background-color: pink;}
h1 {background-color: yellow;}