Full answer
A custom property can be a small public setting for a component. The component reads the property with a fallback, var(--badge-bg, #e6f0ff), so it works with no setup and changes when someone sets the property.
How it works:
- Custom properties inherit. A value set on a parent, on the component itself or on the page flows down to the component.
- The fallback in
var()is used only when the property is not set (or is the guaranteed-invalid value). It is not used when the property is set to a bad value for the property that uses it. In that case, the declaration becomes invalid at computed time and the property falls back to its inherited or initial value. This is a common surprise. - A fallback can itself use
var():var(--badge-bg, var(--color-surface, white)). - Prefix names with the component, such as
--badge-bg, so they do not clash. - Do not set the public property inside the component's own rule on the same element, because that blocks the user's value. Read it with a fallback, and use a private property for internal values.
A clear list of public properties, with defaults, is the interface of the component, like props in a framework.
The first badge uses all defaults. The second changes only the background and keeps the rest. In the third, red is not valid padding, so the padding becomes the initial value 0, and the default 4px 8px is not used.
Check unusual values in your own components, and note in the docs what each property accepts.
<style>
.badge {
--_pad: var(--badge-pad, 4px 8px);
padding: var(--_pad);
background: var(--badge-bg, #e6f0ff);
color: var(--badge-color, #0a2a66);
border-radius: 4px;
display: inline-block;
}
.promo { --badge-bg: #ffe066; }
.broken { --badge-pad: red; }
</style>
<span class="badge" id="a">Default</span>
<span class="badge promo" id="b">Promo</span>
<span class="badge broken" id="c">Broken</span>Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
- Custom properties inherit down the tree.
- var(--x, fallback) uses the fallback when --x is unset.
- An invalid value does not trigger the fallback.
- Prefix names with the component name.
- Do not override the public property inside the component.
Common mistakes
- Expecting the var() fallback to run when a property is set to an invalid value.
- Setting the public property inside the component's own rule, which overrides the user's value.
- Using generic names such as --color that clash across components.
Follow-ups
- What happens to padding when its var() holds an invalid value?
- Why prefix custom property names?
Tips
- Explain that the fallback applies to unset properties, not to invalid values.
- Describe public properties as the component's API.