Sub topic 9
Why dynamic class names fail
This chapter assumes you know basic HTML and CSS, including custom properties, and that you have used Tailwind utilities such as p-4 and bg-blue-500, variants such as hover: and md:, and the square-bracket syntax from the earlier chapters. You do not need to know any particular JavaScript framework. The examples use plain JavaScript and HTML.
By the end you should be able to spot class names that Tailwind will never generate, explain why, and fix them in four ways: complete class names, lookup maps, CSS variables set at runtime, and safelisting.
How Tailwind decides which CSS to generate
Tailwind does not ship a stylesheet containing every possible utility. The set of arbitrary values alone is infinite, since w-[317px], w-[318px] and w-[319px] are all valid. Instead, Tailwind builds a stylesheet that contains only the classes your project uses. To find them, it reads your source files as plain text.
The scanner does roughly this:
- It collects the files to scan. In Tailwind v4 this happens automatically and skips files ignored by
.gitignore,node_modules, binary files, and CSS files. In Tailwind v3 you list the files in thecontentoption oftailwind.config.js. - It splits each file into tokens, which are runs of characters that could be a class name.
- It checks each token against the utilities and variants it knows. A token like
w-[317px]is valid, so Tailwind generates.w-\[317px\] { width: 317px; }. A token likefunctionorconstmatches nothing and is dropped. - It writes the CSS for every valid token to the output stylesheet.
The key point is that the scanner never runs your code. It does not parse JavaScript, evaluate template literals, follow imports, or know what width equals at runtime. It sees characters in a file. Whether those characters sit in an HTML attribute, a JSX string, a Markdown file, or a comment makes no difference.
The failure: interpolating pieces of a class name
Here is the example from the topic plan, expanded to a runnable function.
// Not detected: Tailwind never sees the complete class name
const broken = `w-[${width}px]`;
// Detected: every class name appears in full in the source
const widths = {
narrow: "w-[240px]",
wide: "w-[480px]",
};
const working = widths[size];In the first line, the source text contains the characters `w-[${width}px]. The scanner finds the token w-[${width}px], which is not a valid utility, because ${width} is not a length. Nothing is generated. At runtime, JavaScript produces w-[240px]` and puts it on the element. The browser looks for a rule matching that class, finds none, and the element has no width.
In the second block, the strings "w-[240px]" and "w-[480px]" each appear whole in the file. The scanner finds both and generates both rules. The lookup widths[size] then picks one at runtime, and the CSS is already there.
This is why the failure is quiet. Nothing throws an error, the class name is correct in the DOM inspector, and the build succeeds. Only the CSS rule is missing.
The same mistake in other forms
Any pattern that assembles a class name from smaller strings has the same problem.
| Pattern | Why it fails | Fix |
|---|---|---|
| `` `bg-${color}-500` `` | The source never contains `bg-red-500` or `bg-blue-500` | Map each color to a full class name |
| `"text-" + size` | `text-` alone is not a utility | Write `"text-sm"` and `"text-lg"` in full |
| `` `${bp}:flex` `` | `:flex` and `md:` appear in separate places | Write `"md:flex"` and `"lg:flex"` in full |
| `` `grid-cols-[1fr_${n}px_2fr]` `` | The token contains `${n}`, which is not a length | Use a CSS variable (see below) |
| `` `p-${n * 4}` `` | The computed number never appears in the source | Use a map, or a CSS variable |
| `` `hover:${style}` `` | `hover:` is a fragment | Write `"hover:bg-red-500"` in full |
A useful test: search your project for the exact class name you expect on screen. If you cannot find the whole class as one unbroken string in a scanned file, Tailwind cannot find it either.
Fix 1: write complete class names
The simplest fix is to keep every class name intact and choose between them at runtime. A ternary works, because both branches are complete strings.
function statusClasses(isError) {
return isError ? "bg-red-100 text-red-800" : "bg-green-100 text-green-800";
}A lookup object works the same way and scales better when there are more than two choices. This version is complete and runs in Node or a browser.
const colorClasses = {
info: "bg-sky-100 text-sky-800 border-sky-300",
success: "bg-green-100 text-green-800 border-green-300",
warning: "bg-amber-100 text-amber-800 border-amber-300",
danger: "bg-red-100 text-red-800 border-red-300",
};
function alertClasses(kind) {
return `rounded border p-4 ${colorClasses[kind] ?? colorClasses.info}`;
}
console.log(alertClasses("danger"));
// rounded border p-4 bg-red-100 text-red-800 border-red-300Joining complete strings at runtime, as in the template literal above, is fine. The fixed parts (rounded border p-4) are written in full, and the variable part comes from a lookup. What breaks is building a single class name from fragments.
The lookup object has a second benefit. All the class names for a component sit in one place, so you can read them, grep them, and review them.
Fix 2: pass runtime values through CSS variables
Sometimes the value really is dynamic. It might be a progress percentage from an API, a user-chosen color, or a width computed from the viewport. You cannot list every possibility in a map, and you cannot write the class in advance.
The approach is to write one static class that reads a CSS variable, and set the variable at runtime. The class name never changes. Only the variable's value does. This uses the var() support from the chapter on CSS variables and calc().
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="./output.css" />
</head>
<body>
<div class="w-64 rounded bg-gray-200">
<div
id="bar"
class="h-2 w-[var(--progress)] rounded bg-blue-600 transition-[width]"
></div>
</div>
<script>
function setProgress(percent) {
const clamped = Math.min(100, Math.max(0, Number(percent) || 0));
document
.getElementById("bar")
.style.setProperty("--progress", clamped + "%");
}
setProgress(42);
</script>
</body>
</html>The class w-[var(--progress)] appears in full in the HTML, so Tailwind generates width: var(--progress). JavaScript then sets --progress on the element's inline style. You can change it as often as you like without generating any new CSS.
The same idea works for any property, and you can make the value responsive with an arbitrary property, as shown in the earlier chapter on variants:
<section class="[--scroll-offset:56px] lg:[--scroll-offset:44px] scroll-mt-[var(--scroll-offset)]">
...
</section>When the value is a color or a size, remember the type hints. If you use text-[var(--tone)], Tailwind cannot tell whether the variable holds a color or a font size, so write text-[color:var(--tone)] or text-[length:var(--size)].
Alternatives for runtime values
- An inline
styleattribute is acceptable for a value that is truly one-off and changes at runtime, such asstyle="width: 42%". It cannot use variants likehover:ormd:, so the CSS variable approach is more flexible. - A
data-attribute plus an arbitrary variant works for a small, known set of states. For example,data-[state=open]:bg-blue-600is complete and detectable, and your code only togglesdata-state.
Fix 3: make Tailwind see the classes anyway
Sometimes the full class name genuinely does not appear in a file Tailwind scans. This happens when class names come from a CMS, a database, a design token file in a language Tailwind does not scan, or a third-party package that is excluded from scanning. In those cases, tell Tailwind about them.
In Tailwind v4, use the @source directive in your CSS. To scan an additional directory, such as a UI package inside node_modules:
@import "tailwindcss";
@source "../node_modules/@my-company/ui-lib";To force specific classes into the output even though no scanned file contains them, use @source inline(), which was added in v4.1:
@import "tailwindcss";
@source inline("bg-red-500 bg-blue-500 bg-green-500");In Tailwind v3, the equivalent options are content for extra paths and safelist for specific classes:
// tailwind.config.js
module.exports = {
content: ["./src/**/*.{html,js}", "./node_modules/@my-company/ui-lib/**/*.js"],
safelist: ["bg-red-500", "bg-blue-500", "bg-green-500"],
};Treat safelisting as a last resort. Every safelisted class is always in your CSS, whether used or not, which costs bytes. It also separates the class from the code that uses it, so a later developer who removes the code will not know the safelist entry is now dead. A complete class name in the source is better because the usage and the declaration stay together.
Things that surprise people
Comments and strings count
Because the scan is textual, a class name in a comment or an unused string still generates CSS. Writing // w-[317px] in a file is enough to produce the rule. This is occasionally useful as a deliberate hint, but it can also leave unused CSS in your build. It also means that a package's documentation or test files inside a scanned directory can add classes you did not intend.
Files that are not scanned
If a class works in development and disappears in production, or works in one component and not another, check whether the file holding the class is scanned. Common causes are a file extension missing from the v3 content glob, a source directory listed in .gitignore (v4 skips these), and a shared package in node_modules that you did not add with @source.
Minification and obfuscation of class strings
Tools that rewrite your code, such as string compression or class-name obfuscators, can split or rename strings. Tailwind scans your source, not the bundler output, so this does not usually matter. It does matter if you scan the built output, because the strings may no longer be recognizable.
Underscores and escaping in dynamic strings
An arbitrary value that contains an underscore for a space, like grid-cols-[1fr_500px_2fr], is still one token and is detected normally as long as it is written in full. If you assemble it, as in `grid-cols-[1fr_${w}px_2fr]`, it fails for the same reason as any other interpolation.
How to check whether a class was generated
When a style does not apply, work through these steps in order.
- Open the browser's developer tools and confirm the class is on the element. If it is not, the problem is in your JavaScript, not Tailwind.
- In the Styles panel, check whether any rule matches the class. In the generated CSS, brackets and other special characters are escaped with backslashes, so the selector reads
.w-\[240px\]. - If there is no rule, search your source for the full class name. If you cannot find it as one unbroken string, that is the cause.
- If the full string is there, check that the file is covered by your content configuration or by automatic detection.
- If the rule exists but the value is wrong, the cause is a different issue, such as a missing type hint or an underscore problem, covered in earlier chapters.
A decision guide
| Situation | Approach |
|---|---|
| A small, known set of options such as sizes or variants | Lookup map with complete class names |
| Two options that depend on a boolean | Ternary with complete class names |
| A number or color that comes from data at runtime | Static class that reads a CSS variable, with the variable set at runtime |
| Several states driven by an attribute | `data-[...]:` variants with complete class names |
| Classes that live in a file Tailwind does not scan | `@source` (v4) or `content` (v3) |
| Classes that exist only in a CMS or database | `@source inline()` or `safelist`, kept to a short list |
Summary
Tailwind generates CSS by reading your files as text and keeping every token that is a valid class name. It never executes your code. Any class name that exists only after your code runs, because it was assembled from fragments, is invisible to it. The fix is to write complete class names in the source, choose among them with maps or conditionals, and send truly dynamic values through CSS variables. Safelisting and extra source paths cover the cases where the classes are not in scanned files.
Exercise
A teammate writes <div class={h-[${height}px]}> in a component, where height is 120 or 240. The build passes and the DOM shows h-[120px], but the element has no height. Explain why, and give two different fixes.
Show answer
The scanner reads the file as text and sees h-[${height}px], which is not a valid utility, so it generates no CSS. The browser gets the class h-[120px] at runtime but no rule exists for it. Fix 1: use a map with complete class names, such as { short: "h-[120px]", tall: "h-[240px]" }, and look up the value. Fix 2: write a static class h-[var(--h)] and set the --h variable at runtime, for example with el.style.setProperty("--h", height + "px").
Exercise
Which of these class strings will Tailwind detect, and why? (a) const a = cond ? "bg-red-500" : "bg-blue-500"; (b) const b = "bg-" + color + "-500"; (c) const c = ["md:flex", "lg:grid"][i];
Show answer
(a) and (c) are detected. In both, each class name appears as one complete string in the source, and choosing between them at runtime does not matter. (b) is not detected, because the source contains only the fragments "bg-" and "-500", neither of which is a complete utility.
Exercise
You need a progress bar whose width is any percentage from 0 to 100, sent from a server. Write the HTML class on the bar and the single line of JavaScript that updates it, without generating 101 classes and without an inline width style.
Show answer
Use the class w-[var(--progress)] on the bar, for example <div id="bar" class="h-2 bg-blue-600 w-[var(--progress)]"></div>. Update it with document.getElementById("bar").style.setProperty("--progress", percent + "%");. The class is static and detected, and only the variable's value changes.