Sub topic 5
CSS variables and calc()
This chapter covers the two features that make arbitrary values dynamic: CSS custom properties (also called CSS variables) and calc(). It assumes you know the square-bracket syntax from the previous chapters, including underscores for spaces and length: and color: type hints. It also assumes you are comfortable with custom properties and the cascade in plain CSS.
The examples work in Tailwind v3 and v4 unless a note says otherwise. Where v4 offers a shorter syntax, the note shows it.
Why variables and calc() belong together
A plain arbitrary value such as w-[317px] is fixed at build time. Two CSS features let a value change at runtime without generating new classes:
var(--name)reads a custom property. The browser resolves it when it computes styles, so the value can differ per element, per breakpoint, or per state.calc()combines lengths and numbers, including the result ofvar().
Tailwind only has to generate one CSS rule for the class. The browser does the rest. This matters because of the detection rule covered later in this chapter: Tailwind finds class names by scanning source text, so a class that is complete and static in your source can still produce changing results through variables.
Reading a variable with var()
Put var() inside the brackets as you would in CSS:
<div class="w-[var(--sidebar-w)] bg-[var(--surface)] p-[var(--card-pad)]"></div>Tailwind generates rules such as .w-\[var\(--sidebar-w\)\] { width: var(--sidebar-w); }. Nothing about the variable is checked at build time. If --sidebar-w is never defined, the build succeeds and the browser handles the problem at runtime.
Fallback values
var() accepts a second argument that the browser uses when the variable is not defined:
<div class="w-[var(--sidebar-w,16rem)]"></div>Commas pass through arbitrary values unchanged. If the fallback contains spaces, write them as underscores:
<div class="shadow-[var(--card-shadow,0_1px_3px_rgb(0_0_0/0.2))]"></div>The generated CSS is box-shadow: var(--card-shadow, 0 1px 3px rgb(0 0 0/0.2)).
Shorthand in Tailwind v4
Type hints when the value is a variable
A var() expression gives Tailwind no clue about the type of its value. For utilities that accept more than one type, such as text-*, Tailwind cannot tell whether text-[var(--x)] means font-size or color. Add a type hint before the value, separated by a colon:
<p class="text-[length:var(--hero-size)] text-[color:var(--hero-tone)]">Headline</p>This generates font-size: var(--hero-size) and color: var(--hero-tone). The hint is only an instruction to Tailwind. It does not appear in the output CSS.
Utilities that commonly need a hint with variables:
| Utility | Possible meanings | Hint examples |
|---|---|---|
| `text-` | font size, text color | `text-[length:var(--x)]`, `text-[color:var(--x)]` |
| `bg-` | color, image, size, position | `bg-[color:var(--x)]`, `bg-[length:var(--x)]`, `bg-[position:var(--x)]` |
| `border-` | width, color | `border-[length:var(--x)]`, `border-[color:var(--x)]` |
| `font-` | family, weight | `font-[family-name:var(--x)]`, `font-[weight:var(--x)]` |
In v4 the hint goes before the variable name inside parentheses: text-(length:--hero-size). If you leave out the hint, Tailwind picks a default for the ambiguous case. Do not rely on that default. Write the hint whenever the utility has more than one meaning.
Doing math with calc()
Use calc() for values that mix units, such as a width of "full width minus a gutter":
<div class="w-[calc(100%-2rem)] h-[calc(100vh-4rem)]"></div>In CSS, + and - inside calc() must have spaces on both sides. calc(100%-2rem) is invalid CSS. Tailwind compensates. It adds spaces around the operators when it generates the rule, so w-[calc(100%-2rem)] becomes width: calc(100% - 2rem). That is why left-[calc(50%-2rem)] works in the first example of this tutorial.
You can also write the spaces yourself with underscores, which is clearer when an expression is long:
<div class="w-[calc(100%_-_2rem)] h-[calc(100vh_-_var(--header-h))]"></div>Both forms produce the same CSS. Pick one style and use it consistently in a project.
Combining calc() with variables
Variables turn a fixed formula into a reusable one. Define a value once on an ancestor, then read it with var() inside calc():
<div class="[--header-h:64px]">
<header class="h-[var(--header-h)] bg-[#222]"></header>
<main class="min-h-[calc(100vh-var(--header-h))]">
Content fills the rest of the viewport.
</main>
</div>If the header height changes, you edit one variable and both elements follow. Without the variable, the number 64 would appear in two classes and could drift apart.
Scaling a number into a length
Custom properties can hold unitless numbers. Multiplying by a length gives a length:
<div class="[--cols:3] w-[calc(var(--cols)*6rem)] h-24 bg-[#bada55]"></div>This produces width: calc(var(--cols) * 6rem), which is 18rem. The * and / operators follow the usual calc() rules: at least one side of * must be a plain number, and the right side of / must be a plain number.
Commas and functions
Other CSS math functions work the same way as calc(). min(), max() and clamp() pass through, and commas are preserved:
<div class="w-[clamp(16rem,50%,40rem)] p-[max(1rem,var(--safe-pad,0px))]"></div>Spaces inside these functions are optional after commas, so you usually do not need underscores. You do need them anywhere the CSS value itself contains a space, for example between the parts of a multi-value property.
Setting variables with arbitrary properties
So far the variables came from somewhere else. An arbitrary property, written as [--name:value], lets you define them in the class list:
<section class="[--scroll-offset:56px] lg:[--scroll-offset:44px] scroll-mt-[var(--scroll-offset)]">
...
</section>The class [--scroll-offset:56px] generates --scroll-offset: 56px. The lg: version redefines it from the lg breakpoint up. The utility scroll-mt-[var(--scroll-offset)] never changes. Only the variable changes, and the browser recomputes the margin.
This is the main design pattern for this chapter: keep the property utilities static and vary the variable.
Inheritance and scope
Custom properties inherit. A variable set on a parent is visible to every descendant, which lets you build a small theme for one component:
<article class="[--card-pad:1rem] md:[--card-pad:2rem] [--card-tone:#f4f4f5] dark:[--card-tone:#27272a]">
<h2 class="p-[var(--card-pad)] bg-[color:var(--card-tone)]">Title</h2>
<p class="px-[var(--card-pad)] pb-[var(--card-pad)]">Body text</p>
</article>Both children read the same variables. A child can override a variable for its own subtree by setting it again. Variants work on the definition as well: dark:[--card-tone:#27272a] changes the variable under the dark variant, and every reader of --card-tone updates.
Passing runtime values from JavaScript
Variables also solve the dynamic-class problem for values that are only known at runtime, such as a progress percentage or a measured height. Tailwind cannot generate a class for a value that does not exist at build time, but it does not need to. Keep the class fixed and write the changing value into a variable with inline style:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
</head>
<body class="p-6">
<div class="h-4 w-full bg-[#e4e4e7]">
<div id="bar" class="h-4 w-[var(--progress,0%)] bg-[#bada55]"></div>
</div>
<input id="range" class="mt-4" type="range" min="0" max="100" value="30">
<script>
const bar = document.getElementById("bar");
const range = document.getElementById("range");
function update() {
bar.style.setProperty("--progress", range.value + "%");
}
range.addEventListener("input", update);
update();
</script>
</body>
</html>The class w-[var(--progress,0%)] appears in full in the source, so Tailwind generates it. JavaScript only sets --progress, and the bar resizes as you drag the slider. The fallback 0% keeps the bar defined before the script runs. The last chapter section on class detection explains why the alternative, building w-[${value}%] in a string, fails.
Edge cases and failure modes
An undefined variable fails quietly
If a variable has no value and no fallback, the declaration becomes invalid at computed-value time. For a non-inherited property such as width, the browser then uses the property's initial value, which is auto. Nothing shows up in the build output or the console. When a utility seems to do nothing, open the browser's computed styles and check whether the variable resolves.
Units must be consistent
var() is substituted as text before the value is parsed. Both of these are therefore broken if --n is unitless:
w-[var(--n)]with--n:4giveswidth: 4, which is invalid.w-[calc(var(--n)+2rem)]is invalid, because a bare number cannot be added to a length.
Store the unit in the variable (--n:4rem), or multiply the number by a unit (calc(var(--n)*1rem)).
Percentages depend on the property
calc(100% - 2rem) means different things in width and padding-left, because the browser resolves % against different reference boxes. Tailwind does not change this. If a result looks wrong, check what the percentage refers to for that property.
Spaces inside a variable's value
An arbitrary property that holds a multi-part value needs underscores for spaces, just like any other arbitrary value:
<div class="[--card-shadow:0_4px_12px_rgb(0_0_0/0.15)] shadow-[var(--card-shadow)]"></div>The variable is defined as 0 4px 12px rgb(0 0 0/0.15), and shadow-[var(--card-shadow)] reads it as a whole.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `text-[var(--size)]` for a font size | Tailwind may treat it as a color | `text-[length:var(--size)]` |
| `w-[calc(var(--n)+2rem)]` with unitless `--n` | Invalid at computed-value time | Put the unit in the variable |
| Spaces typed in a class such as `w-[calc(100% - 2rem)]` | The class splits into several tokens | Remove the spaces or use `_` |
| `w-[${x}px]` built in JavaScript | Class is never generated | Set a variable with `style.setProperty` |
| Variable set on a sibling or child | Reader does not inherit it | Set it on a shared ancestor |
Choosing between variables, calc() and theme values
Use a variable when the value changes by context (breakpoint, state, component instance, runtime data) and the utility stays the same. Use calc() when a value is a relation between other values, such as "viewport minus header." If the same number appears in many places across the project, that is a signal to put it in the theme instead, which a later chapter covers.
Exercise
A hero heading must use a font size stored in --hero-size and a color stored in --hero-tone. A teammate wrote class="text-[var(--hero-size)] text-[var(--hero-tone)]" and only one of the two properties applies. Fix it and explain why the original fails.
Show answer
Use class="text-[length:var(--hero-size)] text-[color:var(--hero-tone)]". A var() expression does not tell Tailwind whether text-* means font-size or color, so both original classes are ambiguous and are likely to resolve to the same property. The length: and color: hints select font-size and color explicitly and are not emitted in the CSS.
Exercise
Write the classes for a <main> element that fills the viewport height below a header whose height is 64px on small screens and 48px from the lg breakpoint. The header height must be defined once.
Show answer
On a shared parent, set the variable: [--header-h:64px] lg:[--header-h:48px]. On the header use h-[var(--header-h)]. On <main> use min-h-[calc(100vh-var(--header-h))]. Only the variable changes at lg, and both elements update because they inherit it from the parent.
Exercise
You have a progress value in JavaScript and write bar.className = w-[${pct}%] h-4``. The bar never changes width. What is the smallest change that makes it work?
Show answer
Keep a static class and pass the value through a variable. Use class="w-[var(--progress,0%)] h-4" in the markup and run bar.style.setProperty("--progress", pct + "%") in JavaScript. Tailwind generates the class because it appears in full in the source, and the browser reads the variable at runtime.