Specificity in CSS


I’ve decided to learn few more CSS fundamentals. Decision was made after being annoyed by using !important too much with one CSS framework. First thing was to trying to learn everything about CSS specificity.

It’s the main reason for wondering cluelessly half an hour why some style rule isn’t applied. Than of course you solve it wonderfully with !important keyword. But overusing this keyword makes me feel stupid which I’m certainly not (I have a Bachelor’s degree in Computer sciences after all).

Main source and starting point for learning about specificity was wonderful Smashing Magazine with post dating 6 and 9 years back (CSS Specificity: Things You Should Know and CSS Specificity And Inheritance). This does not mean that they outdated though since basics are basics which doesn’t change over time (that’s also the reason why at school there are classes with literature dating decades back).

Specificity

Specificity determines, which CSS rule is applied by the browsers. If two selectors apply to the same element, the one with higher specificity wins. When selectors have an equal specificity value, the latest rule is the one that counts.

There are four distinct categories which define the specificity level of a given selector:

  1. inline styles
  2. IDs
  3. classes, attributes ([title]), pseudo-classes (:link, :first-child) and
  4. elements, pseudo-elements (:after, :before)

A class selector beats any number of element selectors.

The universal selector and inherited selectors have a specificity of 0, 0, 0, 0.

You can calculate specificity of given selector (e.g. p:first-child #page a:hover):

  • inline styles have specificity of 1000
  • IDs have 100
  • classes and other on same level 10
  • elements and other on same level 1

Examples of specificity values for different selectors

Style sheets can have different sources, here they are ranked by specificity (lowest to greatest).
– user agent (defined by browser)
– user (defined by user settings in browser)
– author (provided by page)
– external (link)
– embedded (in style tag)
– inline (e.g. <p style="color:green">)

If the same selector with the same rule in both author and user style sheets is appended by !important, rule from user style sheet has greater specificity. The reason for this is accessibility.