Topic 18 of 30
Specificity & Cascade
Overview
CSS specificity determines which rule wins when multiple rules target the same element. Understanding it prevents hours of debugging 'why isn't my CSS applying?' issues.
Syntax
css
/* Specificity values (a, b, c):
a = ID selectors
b = class, attribute, pseudo-class
c = element, pseudo-element
#nav .link:hover → (1, 1, 0) → 0-1-1-0
.card .title → (0, 2, 0) → 0-0-2-0
h1 → (0, 0, 1) → 0-0-0-1
*/
/* Hierarchy (highest to lowest): */
/* 1. !important — avoid using */
/* 2. Inline styles style="..." */
/* 3. ID selectors #id */
/* 4. Classes, attributes, pseudo-classes */
/* 5. Elements, pseudo-elements */
/* 6. Universal selector * */Common Pitfalls
- !important overrides everything — it's the nuclear option. Avoid it; it creates technical debt.
- When specificity is equal, the LAST rule in the stylesheet wins.
- Interview tip: The cascade order is: origin (browser/user/author) → specificity → source order. Specificity alone doesn't tell the full story.
Real-World Example
Debugging a specificity conflict in a component library:
example
css
/* Library defines: */
.button { background: blue; } /* (0,1,0) */
/* Your override (same specificity — ORDER matters, yours wins) */
.btn-primary { background: #FFD700; } /* (0,1,0) — later = wins */
/* More specific override */
.card .btn-primary { background: #FFC200; } /* (0,2,0) — higher specificity */
/* AVOID: !important creates maintenance nightmares */
/* .button { background: red !important; } */
/* BETTER: Increase specificity contextually */
.checkout-form .btn-primary {
background: #FFD700;
}