Custom Properties and Specificity
You'll learn: How CSS specificity rules determine which custom property value wins when multiple declarations compete.
How Specificity Affects Custom Properties
Custom properties follow the same cascade and specificity rules as regular CSS properties. When you declare the same custom property in multiple places, the browser uses specificity to decide which value applies—just like it does with color or margin.
Think of it like this: if two people give you different addresses for the same destination, you trust the person with more authority. In CSS, specificity determines that "authority."
The Rules in Action
A custom property declared on :root has low specificity (just one pseudo-class). If you redeclare that same property on a more specific selector, the more specific one wins:
:root {
--main-color: blue;
}
.special-section {
--main-color: red; /* More specific than :root */
}
.special-section .highlight {
--main-color: green; /* Even more specific */
}
Elements inside .special-section .highlight will use green for --main-color, even though :root and .special-section also define it.
Practical Override Patterns
This specificity behavior lets you create contextual overrides. You might set global defaults at :root, then override them for specific components or themes:
:root {
--spacing: 16px;
}
.compact-mode {
--spacing: 8px; /* Override in compact contexts */
}
.generous-mode {
--spacing: 24px; /* Override in generous contexts */
}
Any element using var(--spacing) will get the value from the most specific ancestor that defines it.
Key Takeaway: Custom properties cascade and respect specificity like any CSS property—more specific selectors override less specific ones, letting you create flexible, context-aware design systems.