Cascade & Specificity
Which rule wins and why
Skills taught: css.cascade, css.specificity, css.inheritance
Specificity — the scoring system
Every selector has a specificity score written as three numbers (A, B, C):
- A — number of ID selectors (
#hero) - B — number of class, attribute, and pseudo-class selectors (
.card, [type], :hover) - C — number of element and pseudo-element selectors (
p, ::before)
/* (A, B, C) */
p /* (0, 0, 1) */
.card /* (0, 1, 0) */
#hero /* (1, 0, 0) */
p.lead /* (0, 1, 1) */
#hero .card p /* (1, 1, 1) */
/* Higher A always beats higher B or C — compare left to right */
#hero vs .card.wide.bold → #hero wins (1,0,0) > (0,3,0)
Source order — last one wins
/* Equal specificity — the LATER rule wins */
p { color: red; }
p { color: blue; } /* ← this wins — blue text */
/* Order of <link> tags in HTML also matters */
/* Second stylesheet overrides first for equal specificity */
Inheritance
Some CSS properties are inherited by child elements automatically. Typography properties (color, font-size, font-family) inherit. Layout properties (width, margin, padding) do not.
/* Set font on the parent — all children inherit it */
body {
font-family: Inter, sans-serif;
color: #e2e8f0;
}
/* Explicitly inherit or reset */
button { font-family: inherit; } /* buttons don't inherit by default */
a { color: inherit; } /* links default to blue — override it */
!important — avoid it
/* !important beats ALL other declarations for that property */
p { color: blue !important; } /* this wins, regardless of specificity */
#hero p { color: red; } /* even this loses to !important above */
/* Use !important only for:
- Overriding third-party library styles you cannot touch
- Utility classes that must always win (.hidden { display: none !important; }) */
Warning: Overusing !important creates a specificity war. Every new override needs another !important. It is a sign that your CSS architecture needs refactoring.
Frequently Asked Questions
How do I override a library's styles without !important?
Increase your selector's specificity to beat the library's. If the library uses .btn { color: blue; }, your .my-theme .btn { color: red; } has higher specificity and wins without !important.
What is the 'C' in cascade?
Cascading means styles can come from multiple sources — browser defaults, external files, inline styles — and the cascade algorithm picks which one applies. The 'cascade' is the priority waterfall.
Does inline style always win?
Yes, except for !important declarations in external stylesheets. Inline styles have specificity (1,0,0,0) — higher than any selector.