"Why isn't my CSS applying?" is almost always about the cascade and specificity — the rules that decide which declaration wins when several target the same element. Understanding them turns CSS from guesswork into something you can reason about precisely.
The cascade
When multiple rules set the same property, the winner is decided in this order:
- 1. Importance & origin —
!importantand author vs browser styles. - 2. Specificity — how specific the selector is (below).
- 3. Source order — if specificity ties, the rule written last wins.
Specificity scoring
Specificity is counted as three numbers — (IDs, classes, elements). Compare left to right; a higher earlier number always wins:
| Selector | Specificity | Weight |
|---|---|---|
p | 0,0,1 | element |
.intro | 0,1,0 | class / attribute / pseudo-class |
#lead | 1,0,0 | id |
nav a.active | 0,1,2 | 1 class + 2 elements |
* / :where() | 0,0,0 | no specificity |
p { color: black; } /* 0,0,1 */.intro { color: gray; } /* 0,1,0 → beats the element */#lead { color: navy; } /* 1,0,0 → beats both *//* If two rules tie, the later one in the file wins. */
Inheritance
Some properties pass from a parent to its children automatically — mostly text properties (color, font-family, line-height). Box properties (margin, border, padding) do not inherit. You can force it with the inherit keyword:
body { color: #0f172a; font-family: Inter; } /* children inherit these */button { color: inherit; } /* opt in — buttons don't inherit color by default */.reset { all: unset; } /* strip inherited + default styles */
!important & cascade layers
/* Cascade layers let you order groups of rules explicitly,independent of specificity — great for taming third-party CSS. */@layer reset, base, components, utilities;@layer base { a { color: blue; } }@layer utilities { .text-red { color: red; } } /* later layer wins */
Practice
Write three rules targeting the same element with an element, a class and an id selector; predict which colour shows, then verify. Add a fourth rule with the same specificity later in the file and watch source order break the tie. Then flatten an over-specific rule into a single class.
Key takeaways
- 01The cascade decides winners by importance, then specificity, then source order.
- 02Specificity is (IDs, classes, elements) compared left-to-right; id > class > element.
- 03Text properties inherit (color, font); box properties (margin/padding/border) do not.
- 04Avoid !important — it starts a specificity war; fix the selector instead.
- 05Prefer flat, class-based selectors; @layer orders rule groups independent of specificity.
