How does CSS specificity work?

Specificity determines which CSS rule wins when multiple rules target the same element. It is calculated as a score: inline > ID > class > element.

CSS

Overview

When two or more CSS rules apply to the same element and set the same property, specificity decides which one wins. If specificity is equal, the rule that appears **last** in the stylesheet wins (cascade order).

Key Points

  • •Specificity is a three-part score: (ID, class/attribute/pseudo-class, element/pseudo-element).
  • •Inline styles beat everything (score: 1-0-0-0).
  • •Each ID selector adds (1-0-0): `#header` → score 1-0-0.
  • •Each class, attribute, or pseudo-class adds (0-1-0): `.btn`, `[type="text"]`, `:hover`.
  • •Each element or pseudo-element adds (0-0-1): `div`, `p`, `::before`.
  • •`!important` overrides all specificity - avoid it, it breaks the cascade.

Examples

Specificity scores compared

css
p                    { color: black; }   /* 0-0-1 */
.text                { color: blue; }    /* 0-1-0  wins over p */
#main .text          { color: green; }  /* 1-1-0  wins over .text */
#main p.text:hover   { color: red; }    /* 1-2-1  wins over #main .text */
<p style="color:pink"> ...             /* 1-0-0-0 inline, beats all */

The !important override (avoid)

css
.button { background: blue !important; }
#special .button { background: red; } /* loses, despite higher specificity */

/* !important should be a last resort. Prefer refactoring your selectors. */

Fighting specificity with :is() and :where()

css
/* :is() carries the specificity of its most specific argument */
:is(#main, .section) p { color: blue; } /* specificity of #main = 1-0-1 */

/* :where() always has zero specificity - easy to override */
:where(#main, .section) p { color: blue; } /* specificity = 0-0-1 */

:where() is great for base/reset styles you want to be easily overridden.

Practical tip: keep specificity flat

css
/* Avoid deeply nested selectors */
header nav ul li a:hover { color: red; } /* very high specificity */

/* Prefer a single class */
.nav-link:hover { color: red; } /* much easier to override */

Pro Tip

The best specificity strategy: keep it low and flat. Use a single class for most styling. Avoid IDs in CSS (use them for anchors and JS). Never use `!important` in application code it creates a specificity arms race.