Sub topic 14
Building a reusable fluid scale with custom properties
Earlier chapters used clamp() inline, one declaration at a time. That works for a demo. In a real stylesheet you would repeat the same expressions dozens of times and drift out of sync. This chapter moves those expressions into custom properties, so you define each size once and reuse it everywhere.
This chapter assumes you can write clamp(MIN, PREFERRED, MAX) and know why the preferred value mixes rem and vw. It also assumes you know that var() substitutes a custom property's value.
Why store clamp() in a custom property
A custom property (a name starting with --) stores a value that other declarations read with var(). If the value is a clamp() expression, you get a design token that is fluid by definition. Changing one line retunes every element that uses it.
This gives you three benefits:
- Sizes have names such as
--step-1, so the stylesheet describes intent and not magic numbers. - Tuning happens in one place.
- A scale keeps its proportions, because every step is designed together.
A starter scale
Here is a small type and spacing scale. The type steps grow with the viewport, and the spacing tokens follow the same idea.
:root {
--step-0: clamp(1rem, 0.95rem + 0.25vw, 1.25rem);
--step-1: clamp(1.25rem, 1.1rem + 0.75vw, 1.75rem);
--step-2: clamp(1.5rem, 1.2rem + 1.5vw, 2.5rem);
--space-s: clamp(0.5rem, 0.4rem + 0.5vw, 1rem);
--space-m: clamp(1rem, 0.75rem + 1.25vw, 2rem);
--space-l: calc(var(--space-m) * 2);
}
body {
font-size: var(--step-0);
line-height: 1.5;
}
h1 { font-size: var(--step-2); }
h2 { font-size: var(--step-1); margin-block: var(--space-m); }
section {
padding-block: var(--space-l);
padding-inline: var(--space-m);
}
.cards {
display: grid;
gap: var(--space-s);
grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
}--space-l shows an important technique. A token can be built from another token with calc(). Multiplying a clamp() result by a plain number is valid, and the result still scales fluidly. Doubling --space-m doubles its minimum, maximum, and slope. You can define a whole spacing family from one base value this way.
Note that var() also works inside the arguments of clamp(), min(), and max(). For example, clamp(var(--min), 2vw + 1rem, var(--max)) is valid. This lets you keep the limits in separate properties.
Deriving the numbers instead of guessing
The preferred value should come from a calculation. As the interpolation chapter showed, you choose two points (a size at a narrow viewport, a size at a wide one) and compute a line through them. Doing that by hand for every step is error-prone, so a small helper script is worth having.
This Python script takes sizes and viewport widths in rem and prints the clamp() expression.
def fluid(min_size, max_size, min_vw, max_vw):
"""All arguments are in rem. Assumes min_vw < max_vw."""
slope = (max_size - min_size) / (max_vw - min_vw)
intercept = min_size - slope * min_vw
sign = "+" if intercept >= 0 else "-"
return (
f"clamp({min_size:g}rem, "
f"{abs(intercept):.4g}rem {sign} {slope * 100:.4g}vw, "
f"{max_size:g}rem)"
)
# 1rem at 20rem (320px) up to 2rem at 60rem (960px)
print(fluid(1, 2, 20, 60))
# clamp(1rem, 0.5rem + 2.5vw, 2rem)
# 1.25rem at 20rem up to 1.75rem at 80rem (1280px)
print(fluid(1.25, 1.75, 20, 80))The first call reproduces the worked example from the interpolation chapter. The slope is multiplied by 100 because 1vw is one hundredth of the viewport width. The helper also handles a negative intercept, which happens when the minimum size is large compared to the slope. Paste the output into your :root block.
The calculation assumes a 16px root font size. If a user changes it, the rem terms and limits scale together, which is what you want. The vw term does not scale, so the points where the size reaches its limits shift slightly. That is acceptable.
Where the units are resolved
This is an edge case that catches people. An unregistered custom property stores a sequence of tokens, not a computed length. The tokens are substituted into the property that uses them, and units like em resolve there.
:root {
--pad: clamp(0.5em, 1vw, 2em);
}
.card {
font-size: 2rem;
padding: var(--pad); /* em is relative to .card, so 0.5em = 1rem */
}
.note {
font-size: 0.875rem;
padding: var(--pad); /* the same token, but em is relative to .note */
}The same token produces different padding on .card and .note. Sometimes that is exactly what you want, because the padding scales with the local text size. When it is not, use rem inside your scale tokens. rem always refers to the root, so every element that reads the token gets the same result.
If you register the property with @property and a <length> syntax, the browser computes the value where it is defined, and the computed length is inherited. Most scales do not need this, but it is the tool to reach for when you need em resolved once.
@property --space-m {
syntax: "<length>";
inherits: true;
initial-value: 1rem;
}Overriding the scale in a context
Custom properties follow the cascade. This lets you change a token for one region without touching the components that read it.
.hero {
--step-2: clamp(2rem, 1.4rem + 3vw, 4rem);
}Every element inside .hero that uses var(--step-2) now gets the larger heading size. Elements outside it are unchanged. Override tokens at the scope boundary, and avoid writing special cases in each component.
Naming and organizing
Pick names that describe a position in the scale, not a use. --step-1 and --space-m still make sense after a redesign. --blog-title-size does not.
- Number type steps from the body size (
--step-0), with negative numbers for smaller sizes if you need them. - Use t-shirt sizes (
s,m,l) for spacing, and derive larger sizes withcalc(). - Put all tokens in one
:rootblock or one file so the whole scale can be read at a glance. - Do not store the whole property, such as
--title: 2rem bold. Store single values, so they can be used in any property.
Accessibility and fallbacks
A scale makes it easy to spread one mistake across the whole site, so check the tokens themselves.
- Keep a
remterm in every type token. A preferred value made only ofvwignores the user's font-size setting and zooms poorly. - Check that the maximum is no more than about 2.5 times the minimum. Beyond that, page zoom may not enlarge the text enough to meet WCAG 1.4.4 (resize text).
- Test at 200% zoom and with a larger browser default font size.
Browsers that do not support clamp() are rare now. If you must support them, declare a plain fallback first. A declaration the browser cannot parse is dropped, so the earlier one stays. Be careful with this pattern, though. When a var() is invalid at computed-value time, the property falls back to its inherited or initial value, not to the earlier declaration.
h2 {
font-size: 1.5rem; /* fallback */
font-size: clamp(1.25rem, 1.1rem + 0.75vw, 1.75rem);
}Write the fallback with a literal clamp() as shown, not with var(), when you need it to work. To support old browsers in a token-based scale, wrap the token definitions in @supports (width: clamp(1px, 2px, 3px)), and put plain values in the base rule.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Using `vw` alone in a type token | Text ignores zoom and font settings | Add a `rem` term |
| Using `em` inside a shared token | Value differs per element | Use `rem`, or register with `@property` |
| Writing `--step-1: 1.1rem + 0.75vw` without `clamp()` | Invalid or unbounded when substituted into a property that needs a bare value | Wrap in `clamp()` or `calc()` |
| Inventing numbers by eye | Steps do not reach their limits where intended | Compute the line from two points |
| Naming tokens by use | Names become wrong after a redesign | Name by scale position |
Summary
A fluid scale is a set of named clamp() expressions in :root, derived from two chosen points and read through var(). Derive larger steps with calc(), use rem for consistent results, keep a rem term in type tokens for accessibility, and override tokens at the scope where a different feel is needed.
Exercise
Use the interpolation formula to write a --step-1 token that is 1.25rem at a 20rem (320px) viewport and 2.25rem at a 70rem (1120px) viewport. Give the clamp() expression.
Show answer
slope = (2.25 - 1.25) / (70 - 20) = 1 / 50 = 0.02, which is 2vw. Intercept = 1.25 - 0.02 * 20 = 0.85rem. The token is --step-1: clamp(1.25rem, 0.85rem + 2vw, 2.25rem);
Exercise
A token --gap: clamp(0.5em, 1vw, 1.5em) is used by an element with font-size 1rem and another with font-size 2rem. Why do they get different gaps, and how would you make them equal?
Show answer
The token is unregistered, so its tokens are substituted into each element's declaration, and em resolves against that element's own font size. The 2rem element gets limits twice as large. To make them equal, use rem in the token (clamp(0.5rem, 1vw, 1.5rem)), or register the property with @property and a <length> syntax so it is computed where it is defined.