Sub topic 1
Declaring and Using CSS Custom Properties
Prerequisites
Assume you know basic CSS selectors, properties, values, the cascade, and HTML structure. A custom property is an author-defined CSS value whose name starts with --. You read it with the var() function.
Declaring custom properties and reading them with `var()`
Declare shared values on :root, which represents the document’s root element. This makes the values available throughout the document.
:root {
--brand-color: #0b5fff;
--space: 8px;
}
.button {
background: var(--brand-color);
padding: calc(var(--space) * 2);
}The browser replaces var(--brand-color) with #0b5fff. The calc() function combines --space with another value, producing 16px.
Custom properties follow the cascade. If two declarations apply to the same element, the declaration with higher priority wins.
Providing fallback values
The second argument to var() is a fallback. The browser uses it when the referenced custom property is not defined in the element’s scope.
.card {
color: var(--card-color, #222);
border-color: var(--card-border, var(--brand-color, gray));
}Here, color becomes #222 if --card-color is unavailable. The border uses --card-border if available, then --brand-color, and finally gray.
A fallback is useful when a component can work with a default value but also allows a page or theme to customize it.
Scope and inheritance: where a custom property applies
A custom property applies to the element where it is declared and, by default, inherits into its descendants. A declaration on a component can therefore override a document-wide value for that component.
:root {
--brand-color: #0b5fff;
}
.btn {
--btn-bg: var(--brand-color);
background: var(--btn-bg);
color: white;
}
.btn.danger {
--btn-bg: crimson;
}| Declaration location | Applies to |
|---|---|
| `:root` | The document and its descendants |
| `.btn.danger` | That element and its descendants |
Exercise
What background does a .btn danger element receive if .btn sets --btn-bg to var(--brand-color) and .btn.danger sets it to crimson?
Show answer
It receives crimson, because the more specific local declaration overrides the inherited or earlier value.