Codectionary / Developer documentation / CSS

Specificity

When multiple CSS rules target the same element with conflicting declarations, specificity determines which one wins. It is calculated as a four-part value: inline styles, ID selectors, class/attribute/pseudo-class selectors, and type/pseudo-element selectors, compared in that order from most to least significant.

Syntax

(inline, ID, class, type)

Examples

Comparing Specificity

Working through the specificity of several selectors.

/* p                -> (0,0,0,1) - one type selector */
/* .box              -> (0,0,1,0) - one class selector */
/* #header           -> (0,1,0,0) - one ID selector */
/* .box.featured      -> (0,0,2,0) - two class selectors, higher than one class */
/* #header .box       -> (0,1,1,0) - one ID + one class, beats any class-only combination */

.box.featured { color: blue; }  /* (0,0,2,0) wins over .box alone */
.box { color: red; }             /* (0,0,1,0) loses */

Why !important Should Be a Last Resort

!important overrides normal specificity entirely, which can make future overrides very difficult.

.box { color: red !important; } /* wins regardless of specificity of other rules... */
#header .box.featured { color: blue; } /* ...even against a highly specific selector like this */
/* Now overriding .box requires ANOTHER !important, escalating a maintenance problem */

Best practices

  • Keep specificity as flat and low as possible throughout a project - prefer single class selectors over deeply nested or ID-based selectors
  • Avoid ID selectors for styling entirely in most modern projects, since their high specificity makes later overrides difficult
  • Treat !important as a last resort, not a quick fix - it breaks the normal cascade and often leads to an escalating "specificity war"
  • When two rules genuinely conflict, source order settles ties at equal specificity - the rule declared later in the stylesheet wins

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation