Sub topic 7
Designing Components with Custom Property Hooks
What this chapter assumes
You should already know how to declare a custom property and read it with var(). You should also know how fallback values work and how custom properties inherit down the DOM tree. This chapter combines those pieces into a design pattern. A component exposes a small set of custom properties as its public styling API, and consumers configure the component through those properties instead of overriding its internal selectors.
The problem hooks solve
Suppose you ship a .card component. A teammate wants less padding inside a sidebar. Without a styling API, they write something like this:
.sidebar .card .card-body {
padding: 0.5rem;
}This rule depends on your internal markup, and it needs enough specificity to beat your own rule. It breaks when you rename .card-body. Every consumer ends up coupled to your implementation.
A custom property hook replaces this with a named setting:
.sidebar .card {
--card-padding: 0.5rem;
}The component promises that --card-padding controls its padding. Its internal structure can change without breaking consumers. The custom property is the contract.
Pattern 1: an internal variable that variants redefine
The simplest pattern gives the component a private working variable. It is initialized from a theme-level value, and modifier classes redefine it.
.btn {
--btn-bg: var(--brand-color);
background: var(--btn-bg);
color: white;
}
.btn.danger {
--btn-bg: crimson;
}Every rule that needs the button's background reads --btn-bg. The .btn.danger rule changes the value in that element's scope only. The background declaration itself never changes.
This pattern is good when the component owns its variants. It has a limitation: the declaration --btn-bg: var(--brand-color) sits on .btn itself. A consumer who wants to override it from outside must write a rule that targets the same element and wins the cascade. An ancestor cannot do it, because a declaration on the element beats an inherited value.
Pattern 2: fallbacks as defaults
The second pattern avoids declaring the hook on the component at all. The component only reads it, and the second argument of var() supplies the default.
.card {
padding: var(--card-padding, 1rem);
border-radius: var(--card-radius, 8px);
background: var(--card-bg, var(--surface, white));
border: 1px solid var(--card-border-color, #ddd);
}Nothing sets --card-padding by default, so the fallback 1rem applies. A consumer can set the property in several places, and all of them work:
/* On an ancestor, affecting every card inside it */
.sidebar {
--card-padding: 0.5rem;
}
/* On one card through a class */
.card.compact {
--card-padding: 0.25rem;
}<!-- On one card through an inline style -->
<div class="card" style="--card-padding: 2rem">Roomy card</div>The nested fallback on --card-bg shows a useful layering. The component first looks for its own hook. Then it looks for a shared theme token, --surface. Then it uses a literal value. The component works in a project with no theme and picks up the theme when one exists.
The diagram below shows this lookup order.
Choosing between patterns 1 and 2
| Question | Internal variable (pattern 1) | Fallback hook (pattern 2) |
|---|---|---|
| Where is the property declared? | On the component | Nowhere by default |
| Can an ancestor configure it? | No, the component's own declaration wins | Yes |
| Is the default easy to see? | In one declaration | Repeated at each `var()` use |
| Best for | Variants the component owns | Settings consumers tune from outside |
You can combine them. Read a public hook with a fallback, and keep the working variable private:
.btn {
--_bg: var(--btn-bg, var(--brand-color, #0b5fff));
background: var(--_bg);
border-color: var(--_bg);
}Here --btn-bg is the public hook and --_bg is private by convention. The default is written once, and every rule that needs the color reads --_bg.
Why scope and inheritance make this work
Custom properties inherit by default. A value set on .sidebar flows to every descendant that does not set its own value. The component reads the property at its own element, so the nearest definition up the tree wins.
This gives you three levels of configuration without extra code:
- Global: set the hook on
:rootand every instance changes. - Regional: set it on a container and instances inside it change.
- Local: set it on one instance through a class or inline style.
Because resolution is per element, the same component can show different values on the same page with no coordination.
Pattern 3: derived values with calc()
A good hook is a single knob that drives several related values. Define one base setting and derive the rest from it.
.btn {
--btn-pad: var(--btn-size, 0.5rem);
padding: var(--btn-pad) calc(var(--btn-pad) * 2);
border-radius: calc(var(--btn-pad) / 2);
font-size: calc(0.75rem + var(--btn-pad) / 2);
}
.btn.large {
--btn-size: 0.875rem;
}Consumers change one number, and the padding, radius, and font size stay in proportion. Offering one hook instead of four also keeps the API small and keeps consumers from producing inconsistent combinations.
Note that calc() needs a value with a unit where the math requires one. --btn-size: 0.875 without rem would make calc(0.75rem + 0.875 / 2) invalid. Document the expected type of each hook.
A complete example
This page defines an alert component with public hooks, private derived values, and two usage contexts. It runs as written in a browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Alert component</title>
<style>
:root {
--brand-color: #0b5fff;
}
/* Public hooks: --alert-accent, --alert-bg, --alert-pad */
.alert {
--_accent: var(--alert-accent, var(--brand-color, #0b5fff));
--_pad: var(--alert-pad, 1rem);
padding: var(--_pad);
border-left: calc(var(--_pad) / 4) solid var(--_accent);
background: var(--alert-bg, #f4f6fb);
color: #111;
margin: 1rem 0;
}
.alert-title {
color: var(--_accent);
font-weight: bold;
}
/* Variants set the public hook */
.alert.warning {
--alert-accent: darkorange;
}
/* A region configures every alert inside it */
.compact-area {
--alert-pad: 0.5rem;
}
</style>
</head>
<body>
<div class="alert">
<div class="alert-title">Default</div>
Uses the brand color and default padding.
</div>
<div class="alert warning">
<div class="alert-title">Warning</div>
A variant sets the accent hook.
</div>
<div class="compact-area">
<div class="alert" style="--alert-bg: #fff8e1">
<div class="alert-title">Compact</div>
The region sets padding. The inline style sets the background.
</div>
</div>
</body>
</html>Each of the three configuration levels appears here. The .warning class sets the hook on one instance. The .compact-area wrapper configures a region. The inline style attribute changes a single element.
Pitfall: inheritance leaks into nested components
Inheritance is a feature, but it can surprise you with nested components. If a .sidebar sets --card-bg: lightyellow, every card inside it picks up that color, including a card nested inside another card. You may have meant only the outer one.
The same leak happens when two components use the same generic name. If a card reads --bg and a theme also defines --bg for the page, the card changes color unexpectedly.
Prevent this in three ways:
- Prefix every hook with the component name, such as
--card-bg, not--bg. - Reset a hook on the component when you do not want to receive it from ancestors.
- Register the property with
inherits: falseusing@property, which a later chapter covers.
For the reset option, the keyword initial returns an unregistered custom property to its guaranteed-invalid state. A var() call that reads it then falls back to its default:
.card .card {
--card-bg: initial;
}The inner card ignores any --card-bg set above it and uses the fallback in its var() call.
Pitfall: specificity on the component's own declaration
In Pattern 1, if the component declares --btn-bg on .btn and a consumer sets --btn-bg on .toolbar, the consumer loses. The .btn rule applies directly to the element. The .toolbar value is only inherited, and inherited values are used only when the element has no declaration of its own.
The fix is to separate the public name from the private one, as in the --_bg example earlier. The component declares only the private property, so the public one remains free to inherit from anywhere.
Pitfall: invalid values break the whole declaration
If a consumer supplies a value of the wrong type, the failure does not happen where they set it. It happens where var() is used. Suppose a consumer writes --card-padding: wide. The browser accepts that without complaint, because custom properties take any value. When padding: var(--card-padding, 1rem) is evaluated, wide is not a valid padding. The declaration becomes invalid at computed-value time. The 1rem fallback does not apply, because the fallback is used only when the property is missing, not when it holds a bad value. The padding resets to its inherited or initial value.
Mitigations:
- Document the type of each hook in a comment.
- Prefer hooks that accept a small set of values, and expose them through classes or attributes.
- Register typed properties with
@propertywhen you need the browser to validate the value and fall back toinitial-value.
Naming and documenting the API
A few conventions keep a hook API maintainable:
- Use a component prefix:
--card-,--btn-,--alert-. - Name by purpose, not by value. Use
--btn-bg, not--btn-blue. - Mark private properties with a leading underscore, such as
--_accent. This is a convention only. CSS does not enforce privacy, and consumers can still set these values. - Keep the public list short. Each hook is a promise you must keep across releases.
- List the hooks at the top of the component's stylesheet, with the expected type and the default for each.
/*
* .card hooks
* --card-padding <length> default 1rem
* --card-radius <length> default 8px
* --card-bg <color> default var(--surface, white)
* --card-border-color <color> default #ddd
*/
.card {
padding: var(--card-padding, 1rem);
border-radius: var(--card-radius, 8px);
background: var(--card-bg, var(--surface, white));
border: 1px solid var(--card-border-color, #ddd);
}Summary of decisions
- Use a fallback hook (Pattern 2) when consumers need to configure the component from ancestors or inline styles.
- Use an internal variable (Pattern 1) for variants the component controls.
- Combine them with a private working property when the same value appears in several rules.
- Derive related values from one hook with
calc(). - Prefix names to avoid collisions, and reset with
initialwhen inheritance is unwanted.
Exercise
A component declares .tag { --tag-bg: gray; background: var(--tag-bg); }. A page author writes .toolbar { --tag-bg: teal; } and puts a .tag inside the toolbar, but the tag stays gray. Explain why, and rewrite the .tag rule so the toolbar setting works while gray remains the default.
Show answer
The .tag rule declares --tag-bg directly on the element, so the element has its own value and does not use the value inherited from .toolbar. Read the hook with a fallback and do not declare it on the component: .tag { background: var(--tag-bg, gray); }. With no value set, the fallback gray applies. When .toolbar sets --tag-bg: teal, the tag inherits it and turns teal.
Exercise
A card reads padding: var(--card-padding, 1rem). A consumer sets --card-padding: wide. What padding does the card get, and why does the 1rem fallback not apply?
Show answer
The padding resets to its inherited or initial value, which for padding is 0, not 1rem. The fallback applies only when the custom property is undefined or holds the guaranteed-invalid value. Here the property is defined as wide, so var() substitutes it. The result, padding: wide, is invalid, so the declaration is invalid at computed-value time.
Exercise
Design a single hook for a badge so that its horizontal padding is twice the vertical padding and its border radius is half the vertical padding. Write the CSS, using a public hook named --badge-pad with a default of 0.25rem.
Show answer
.badge {
--pad: var(--badge-pad, 0.25rem);
padding: var(--pad) calc(var(--pad) * 2);
border-radius: calc(var(--pad) / 2);
}
Consumers then set one value, such as --badge-pad: 0.5rem, and all three measurements stay in proportion.