Episode 11 of 53
Specificity of Rules
Learn how CSS specificity determines which styles win when selectors conflict.
Specificity is the algorithm CSS uses to decide which rule takes priority when multiple rules target the same element with conflicting properties.
The Specificity Hierarchy
Each selector type has a different weight. From lowest to highest:
- Element selectors —
p,h1,div→ specificity:0-0-1 - Class selectors —
.card,.active→ specificity:0-1-0 - ID selectors —
#header,#main→ specificity:1-0-0
Calculating Specificity
p { } /* 0-0-1 */
.intro { } /* 0-1-0 */
p.intro { } /* 0-1-1 */
#header { } /* 1-0-0 */
#header .nav li { } /* 1-1-1 */
Higher specificity always wins, regardless of source order.
Practical Example
/* Specificity: 0-0-1 */
p { color: black; }
/* Specificity: 0-1-0 — this wins! */
.special { color: red; }
/* Even though p comes first, .special has higher specificity */
Tips
- Avoid using IDs for styling — their high specificity makes overriding difficult
- Prefer classes — they're reusable and have moderate specificity
- Keep selectors as simple as possible