Sub topic 3
Designing Components with CSS Custom Property Hooks
Assume you know CSS selectors, the cascade, inheritance, basic HTML, and basic JavaScript DOM access. This chapter focuses on using custom properties as component configuration points.
Designing a Component API
A custom property hook is a custom property that a component intentionally exposes for callers to change. Keep internal details private and document the supported hooks.
:root {
--brand-color: #0b5fff;
}
.btn {
--btn-bg: var(--brand-color);
--btn-padding: 0.75rem 1rem;
background: var(--btn-bg);
color: white;
padding: var(--btn-padding);
border: 0;
border-radius: 0.4rem;
}
.btn.danger {
--btn-bg: crimson;
}The .btn rule defines defaults. The modifier changes only the button's scope. A parent can also provide a value:
.panel {
--btn-padding: 1rem 1.5rem;
}Custom properties inherit by default, so descendants can read values from their ancestors. Set component-specific properties on the component itself when inheritance could create unexpected coupling.
Working from JavaScript
Use setProperty() to write a custom property. Use getComputedStyle() to read its resolved value.
const root = document.documentElement;
root.style.setProperty("--brand-color", "#e91e63");
const color = getComputedStyle(root)
.getPropertyValue("--brand-color")
.trim();
console.log(color);This changes an inline declaration. It can override stylesheet values according to the normal cascade.
Registering and Animating Typed Properties
Unregistered custom properties are treated mostly as unparsed tokens. Registering one gives the browser its type, inheritance behavior, and initial value.
@property --angle {
syntax: "<angle>";
inherits: false;
initial-value: 0deg;
}
.spinner {
transform: rotate(var(--angle));
transition: --angle 0.4s ease;
}
.spinner:hover {
--angle: 180deg;
}The browser can interpolate the two angles, producing a smooth rotation.
Limitations and Common Pitfalls
var()works in property values, not media query conditions. Use media queries to redefine tokens instead.- A value can look valid until substitution. If substitution makes the final property invalid, the browser discards that declaration.
var(--x, fallback)uses the fallback when--xis missing or invalid in that context. It does not validate every possible token.- Custom properties inherit unless registered with
inherits: false. - Registration syntax and browser support should be checked before relying on
@propertyin production.
Exercise
Why does .btn.danger change the button without changing every rule that uses the background color?
Show answer
It redefines the scoped --btn-bg custom property, while background: var(--btn-bg) remains unchanged.