Understand the idea
Custom properties hold reusable values. Their names begin with two hyphens, and var() retrieves a value where it is needed.
Properties declared on :root are available throughout the document through inheritance. A more local declaration can override a value for one component. A fallback in var() applies when the referenced custom property is missing or invalid as a custom property; it is not a general repair for every invalid CSS value. These examples use ordinary, unregistered custom properties. Registration with @property can change inheritance, syntax checking and initial values.
Read the example
This is a CSS fragment. Put it in a stylesheet and supply the matching HTML described in the exercise.
:root {
--accent: #6542d7;
--space: 1rem;
}
.card {
padding: var(--space);
border: 2px solid var(--accent, purple);
}A small mistake, explained
What goes wrong
--Accent and --accent are different names. A small case change can leave a reference unresolved.
How to fix it. Compare the spelling exactly. Inspect the computed value and add an intentional fallback where appropriate.
Try it yourself
Change --accent once. Then override it on a wrapper around just one card.
Further reading
W3C — CSS Custom Properties (new tab)
Keep exploring
- CSS · Guide
Find the source of horizontal overflowFix the oversized element instead of hiding the symptom.
- CSS · Guide
Why a huge z-index can still loseUnderstand the group an element belongs to before raising its number.