Sub topic 5
Building scales with calc() and other functions
This chapter assumes you can declare custom properties and read them with var(), and that you understand inheritance. It also assumes you know basic CSS units (px, rem, %, vw). Here you will use custom properties as the inputs to calculations. The goal is spacing, type, and color scales that you change in one place.
Why compute values
Hard-coded values such as 8px, 16px, 24px, and 32px drift over time. Someone adds 20px because it looks right, and the system stops being a system.
A scale fixes this by storing a small number of base values and deriving everything else from them. Custom properties hold the base values. CSS math functions (calc(), min(), max(), clamp()) and color functions combine them.
calc() with var()
When the browser substitutes a custom property into calc(), it works with the property's tokens. So var() can stand in for a number, a length, or a percentage anywhere calc() accepts one.
:root {
--space-unit: 4px;
}
.card {
padding: calc(var(--space-unit) * 4);
margin-block: calc(var(--space-unit) * 6);
gap: calc(var(--space-unit) * 2);
}Four rules from calc() itself apply here:
+and-need whitespace on both sides.calc(1px+2px)is invalid.*and/do not need whitespace, but adding it is a good habit.- In a multiplication, at least one side must be a plain number. In a division, the right side must be a plain number.
calc(4px * 2px)is invalid. - You cannot negate with a leading minus sign:
-var(--space)is invalid. Multiply by-1instead. - A
calc()that mixes types, such ascalc(100% - var(--space-unit)), is resolved at layout time. This is how you combine percentages with fixed lengths.
.sidebar-offset {
margin-left: calc(var(--space-unit) * -2);
width: calc(100% - var(--space-unit) * 10);
}Unitless numbers are the most flexible
A custom property that holds a bare number can be paired with any unit. This makes it useful as a multiplier:
:root {
--cols: 3;
--gutter: 16;
}
.grid {
display: grid;
grid-template-columns: repeat(var(--cols), 1fr);
gap: calc(var(--gutter) * 1px);
}Do not try to attach a unit by writing it next to the variable. var(--gutter)px does not become 16px. The substitution produces the tokens 16 and px as separate pieces, so the declaration is invalid. Multiply by a unit instead: calc(var(--gutter) * 1px), or * 1rem, or * 1deg.
Deriving a spacing scale
You can store a base unit and derive named steps from it:
:root {
--space-unit: 0.25rem;
--space-1: var(--space-unit);
--space-2: calc(var(--space-unit) * 2);
--space-3: calc(var(--space-unit) * 3);
--space-4: calc(var(--space-unit) * 4);
--space-6: calc(var(--space-unit) * 6);
--space-8: calc(var(--space-unit) * 8);
}
.stack > * + * {
margin-top: var(--space-4);
}
.panel {
padding: var(--space-6) var(--space-8);
}Changing --space-unit to 0.3rem rescales every step. Components refer to --space-4, not to calc(...), so the multipliers appear only once.
The derived-value trap
There is an important gotcha here, and it follows from the scope rules in the previous chapters. When a custom property's value contains var(), the browser substitutes it on the element where the property is declared. Descendants then inherit the result, not the formula.
The scale above is declared on :root. --space-4 therefore becomes calc(0.25rem * 4) on the root. If a descendant overrides --space-unit, --space-4 does not change:
.compact {
--space-unit: 0.125rem; /* --space-4 inside .compact is still 1rem */
}You have two ways to get the behavior you probably expected:
- Redeclare the derived properties in the same rule that changes the base. This is tedious and easy to forget.
- Compute at the point of use, as in
padding: calc(var(--space-unit) * 4). Here the formula is evaluated on the element that uses it, so it sees the overridden base.
A third option is to declare the derived properties on a selector that matches every element in the scope you want to rescale, such as .compact, .compact *. This works but is heavy. Decide up front whether a scale needs to be rescalable inside components. If it does, avoid pre-computing the steps on :root.
A modular type scale
A modular scale multiplies a base size by a fixed ratio for each step. Custom properties express that directly:
:root {
--step-0: 1rem;
--ratio: 1.25;
--step-1: calc(var(--step-0) * var(--ratio));
--step-2: calc(var(--step-1) * var(--ratio));
--step-3: calc(var(--step-2) * var(--ratio));
}
h1 { font-size: var(--step-3); }
h2 { font-size: var(--step-2); }
h3 { font-size: var(--step-1); }
p { font-size: var(--step-0); }With a ratio of 1.25, the steps come out to 1.25rem, 1.5625rem, and 1.953125rem. The browser works this out for you, so you can change --ratio to 1.333 and the whole scale follows. As in the previous section, this holds only for the scope where the derived steps are computed.
Negative steps
For sizes below the base, divide by the ratio. The divisor must be a plain number, and --ratio is one:
:root {
--step-minus-1: calc(var(--step-0) / var(--ratio));
}
small {
font-size: var(--step-minus-1);
}min(), max(), and clamp()
The comparison functions accept custom properties in the same way. Inside them, the math operators work without wrapping the expression in calc():
| Function | Returns | Typical use |
|---|---|---|
| `min(a, b)` | The smaller value | A width that never exceeds a limit |
| `max(a, b)` | The larger value | A size that never falls below a limit |
| `clamp(lo, preferred, hi)` | `preferred`, held between `lo` and `hi` | Fluid type and fluid spacing |
:root {
--content-max: 60rem;
--page-gutter: 1rem;
}
.container {
width: min(100% - 2 * var(--page-gutter), var(--content-max));
margin-inline: auto;
}The container is as wide as the viewport minus a gutter on each side, up to a maximum of 60rem. Both numbers can be changed from the custom properties.
Fluid scales with clamp()
clamp() lets a size grow with the viewport between two limits. Store the three arguments in custom properties and use them as steps:
:root {
--fluid-text: clamp(1rem, 0.9rem + 0.5vw, 1.25rem);
--fluid-heading: clamp(1.75rem, 1.2rem + 2.5vw, 3rem);
--fluid-space: clamp(1rem, 0.5rem + 2vw, 2.5rem);
}
body {
font-size: var(--fluid-text);
}
h1 {
font-size: var(--fluid-heading);
}
section {
padding-block: var(--fluid-space);
}The clamp() is stored as tokens and evaluated where it is used. Because vw units resolve against the viewport, not the element, the result is the same wherever it appears. Relative units like em would resolve against the font size of the element that uses the property, which can surprise you if the property is declared on a different element than the one that consumes it.
Avoid sizing text with vw alone. Text that cannot be zoomed is an accessibility problem. Combining rem with vw, as above, keeps the size responsive to the user's zoom and font settings.
Color scales
Custom properties work well for color when you split a color into its parts. Keeping the hue as a number lets you build a whole palette from it:
:root {
--hue: 220;
--sat: 80%;
}
.badge {
background: hsl(var(--hue) var(--sat) 92%);
color: hsl(var(--hue) var(--sat) 25%);
border: 1px solid hsl(var(--hue) var(--sat) 70%);
}
.badge.warning {
--hue: 35;
}The modifier class changes --hue, and all three colors move with it. This uses the space-separated hsl() syntax, which current browsers support.
When you have a finished color and want variations, color-mix() blends two colors in a chosen color space:
:root {
--brand: #0b5fff;
--brand-soft: color-mix(in srgb, var(--brand) 15%, white);
--brand-strong: color-mix(in srgb, var(--brand) 80%, black);
}
.link {
color: var(--brand-strong);
background: var(--brand-soft);
}The percentage says how much of the first color to use. The rest comes from the second. color-mix() and relative color syntax are newer than calc(), so check browser support for your audience. A fallback declaration placed before the modern one is a good practice.
.link {
background: #e6efff;
background: var(--brand-soft);
}If var(--brand-soft) cannot be resolved, the second declaration is invalid at computed-value time. In that case the browser does not fall back to the first declaration. The fallback therefore works only when the browser does not understand the function at all, and does not help when a variable is missing. The next chapters on substitution and pitfalls explain the difference.
Common mistakes
- Zero without a unit.
calc(var(--a) + 0)is invalid when--ais a length, because0is a number in a calculation. Use0px, orcalc(var(--a) + 0px). - Assuming arithmetic happens in the declaration.
--double: 2 * 4;does not store8. Unregistered custom properties keep their text. Wrap the math incalc()where you use it, as incalc(2 * 4). A registered type, covered in a later chapter, can change how the value is handled. - Mixing types in a multiplication.
calc(var(--space) * var(--space))fails if both are lengths. At least one side must be a number. - Forgetting spaces around
+and-. Both operators require them, including whenvar()is involved. - Pre-computing on
:rootand expecting overrides to flow through. See the derived-value trap above.
Putting it together
This stylesheet combines a unit, a ratio, a fluid size, and a hue into one small design system. All of the multipliers sit in one place:
:root {
--space-unit: 0.25rem;
--ratio: 1.25;
--hue: 220;
--page-max: 70rem;
}
.page {
width: min(100% - calc(var(--space-unit) * 8), var(--page-max));
margin-inline: auto;
padding-block: clamp(1rem, 0.5rem + 2vw, 3rem);
}
.page h2 {
font-size: calc(1rem * var(--ratio) * var(--ratio));
margin-bottom: calc(var(--space-unit) * 3);
color: hsl(var(--hue) 70% 30%);
}
.page .note {
padding: calc(var(--space-unit) * 4);
background: hsl(var(--hue) 70% 94%);
border-left: calc(var(--space-unit)) solid hsl(var(--hue) 70% 50%);
}Here the formulas are evaluated at the point of use, so an override of --space-unit or --hue on a section changes every dependent value inside that section.
Exercise
A stylesheet declares :root { --space-unit: 4px; --space-3: calc(var(--space-unit) * 3); }. A rule .dense { --space-unit: 2px; } sets a smaller base. Inside .dense, padding: var(--space-3) still gives 12px. Why, and how would you change the stylesheet so .dense gives 6px?
Show answer
--space-3 contains var(), so it is substituted on :root, where --space-unit is 4px. The computed value calc(4px * 3) is inherited by .dense, so the override never reaches it. Two fixes work. You can write the formula where it is used, padding: calc(var(--space-unit) * 3), so it evaluates against the nearest --space-unit. Or you can redeclare --space-3: calc(var(--space-unit) * 3) inside .dense.
Exercise
You store --gap: 12; and want a 12px gap. Which declaration is valid: gap: var(--gap)px;, gap: calc(var(--gap) * 1px);, or gap: -var(--gap);? Then write a declaration that gives the same gap with the opposite sign.
Show answer
gap: calc(var(--gap) * 1px); is the valid one. var(--gap)px is two separate tokens, and -var(--gap) is not a valid negation. For the opposite sign, use calc(var(--gap) * -1px). Note that gap does not accept negative values, so use the negative form on a property such as margin-left.
Exercise
Write a custom property --fluid-space that is never smaller than 1rem and never larger than 2.5rem, and grows with the viewport between those limits. Then use it as vertical padding.
Show answer
Declare --fluid-space: clamp(1rem, 0.5rem + 2vw, 2.5rem); on :root, then write padding-block: var(--fluid-space); in the rule that needs it. The middle argument supplies the growth, and clamp() holds the result between the first and third arguments.