Why Specificity Matters
When more than one CSS rule matches the same element and sets the same property, the browser must decide which one to apply. This decision is based on specificity, source order, and importance.
A Specificity Conflict
<style>
p { color: blue; }
.note { color: green; }
#warning { color: red; }
</style>
<p id="warning" class="note">
This text is red — the ID selector wins.
</p>How Specificity is Calculated
Specificity is often represented as three numbers, from most to least powerful: ID selectors, class/attribute/pseudo-class selectors, and type/pseudo-element selectors. More of a stronger category always beats any amount of a weaker one.
Specificity Categories (Strongest to Weakest)
| Category | Examples | Weight |
|---|---|---|
| Inline style | style="color: red" | Highest (beats all selectors) |
| ID selectors | #header | 1-0-0 |
| Classes, attributes, pseudo-classes | .btn, [type="text"], :hover | 0-1-0 |
| Type selectors, pseudo-elements | div, ::before | 0-0-1 |
Comparing Specificity
/* 0-0-1 */
p { color: black; }
/* 0-1-0 — wins over the type selector above */
.highlight { color: orange; }
/* 1-0-0 — wins over both rules above */
#unique { color: purple; }Source Order
When two rules have equal specificity, the one that appears later in the stylesheet wins. This is the "cascading" part of Cascading Style Sheets.
Equal Specificity, Order Decides
<style>
.box { color: blue; }
.box { color: green; } /* wins — same specificity, comes later */
</style>
<p class="box">This text is green.</p>The !important Escape Hatch
Adding !important to a declaration overrides normal specificity rules almost entirely. It should be used sparingly — overusing it makes styles unpredictable and hard to override later, often forcing more !important rules to fix.
Best Practice
Keep selectors as low-specificity as possible (favor classes over IDs and deep nesting) so later overrides stay easy, and avoid !important except as a last resort.