Sub topic 11
Dynamic class names and how Tailwind detects classes
This chapter assumes you know basic HTML and CSS, can run npm scripts, and have set up Tailwind in a project as covered in the setup chapter. Familiarity with JavaScript template strings and a component framework helps, but you can follow the examples without one.
By the end, you will be able to explain how Tailwind decides which CSS to generate, spot class names it cannot see, and fix them with patterns that work in any framework.
How Tailwind finds classes
Tailwind does not run your code. It reads your source files as plain text and looks for strings that could be class names. For each candidate, it checks whether a utility with that name exists. If one does, Tailwind writes the matching CSS rule into the output. If none does, the string is ignored.
This design keeps the final stylesheet small, because only the utilities you actually use are generated. It also means Tailwind can scan any file type: HTML, JavaScript, TypeScript, JSX, Vue, Svelte, PHP, Markdown, and so on.
The scanner works in three steps:
- It collects the files to scan. In Tailwind v4 this happens automatically, and it skips files listed in
.gitignore,node_modules, binary files, CSS files, and lock files. - It splits each file's text into tokens, which are runs of characters that could form a class name.
- It checks each token against the set of known utilities and variants, then generates CSS for the matches.
Because the scanner treats your files as text, it has no idea what your JavaScript will do at runtime. It cannot evaluate expressions, follow variables, or join strings together. The class name must already exist, spelled out in full, somewhere in a scanned file.
The core rule: write complete class names
Tailwind can only generate a class if the complete name appears literally in the source. Fragments that your code later joins together are invisible to it.
// Does not work: Tailwind cannot see the full class name in the source.
const bad = (color) => `text-${color}-600`;
// Works: every complete class name appears literally in the source.
const colorClasses = {
red: 'text-red-600',
green: 'text-green-600',
};
const good = (color) => colorClasses[color];In the first function, the source contains the text text-, then -600. Neither is a utility. The string text-red-600 only exists after the function runs in the browser, and by then the build is long finished. The page renders with a class name that has no CSS behind it, so the element looks unstyled, and nothing reports an error.
In the second version, text-red-600 and text-green-600 both appear in full inside the object. The scanner finds them, generates the rules, and the lookup at runtime simply picks one of two classes that already exist in the stylesheet.
Common ways to break detection
| Pattern | Why it fails | Fix |
|---|---|---|
| `` `bg-${color}-500` `` | The color is joined at runtime | Map each value to a full class string |
| `'px-' + size` | Concatenation hides the full name | Use a lookup object |
| `` `grid-cols-${n}` `` | The number is a variable | List `grid-cols-2`, `grid-cols-3` in full |
| Class names built from API data | The values exist only at runtime | Map known values to classes, or use a safelist |
| `'hover:' + cls` | The variant prefix is joined at runtime | Write each `hover:` class in full |
A useful check is to search your project for the exact class name. If you cannot find it with a plain text search, Tailwind cannot find it either.
What does work
Tailwind scans text, not syntax, so any place the full name appears counts. All of these are detected:
const sizes = {
sm: 'px-2 py-1 text-sm',
md: 'px-4 py-2 text-base',
lg: 'px-6 py-3 text-lg',
};
const isActive = true;
const className = isActive ? 'bg-indigo-600 text-white' : 'bg-slate-200 text-slate-800';
const states = ['opacity-50', 'opacity-100'];Conditional expressions, arrays, object values, and comments are all fine, because the complete class names are present in the file. Even a name inside a comment is detected, which can produce a little unused CSS. That is harmless.
Props that change styles
The most common place this problem appears is a component that takes a prop such as color or size. Passing the class fragment as the prop is tempting, but it breaks detection.
// Fragile: the caller passes only a fragment.
function Button({ color, children }) {
return `<button class="bg-${color}-600 text-white">${children}</button>`;
}Instead, have the component map a small set of meaningful names to complete classes.
const variants = {
primary: 'bg-indigo-600 hover:bg-indigo-700 text-white',
danger: 'bg-red-600 hover:bg-red-700 text-white',
neutral: 'bg-slate-200 hover:bg-slate-300 text-slate-900',
};
function Button({ variant = 'primary', children }) {
return `<button class="rounded-lg px-4 py-2 ${variants[variant]}">${children}</button>`;
}
console.log(Button({ variant: 'danger', children: 'Delete' }));This approach has benefits beyond detection. Callers choose from a named list instead of passing arbitrary strings, so the design stays consistent. Adding a new variant means adding one line in one place.
If the caller does need to pass classes directly, pass full class names as the prop value, such as className="bg-red-600". The string then appears whole in the file where the caller wrote it.
Dynamic values that really are dynamic
Sometimes a value truly cannot be known at build time. Examples are a user-chosen color, a progress percentage, or a height from a database. Class names are the wrong tool here, because there are infinitely many possible values. Use an inline style, or a CSS variable set inline and consumed by a utility.
<div class="h-2 rounded bg-slate-200">
<div class="h-2 rounded bg-indigo-600 w-[var(--progress)]" style="--progress: 65%"></div>
</div>The utility w-[var(--progress)] is written in full, so Tailwind generates it. The page sets the variable at runtime. The class stays static and only the value changes. This is a good pattern for any number that comes from data.
A plain style="width: 65%" also works and is fine for a single property. The CSS variable approach is better when several utilities or variants should react to the same value.
Telling Tailwind where to look
By default, the v4 scanner works out sources from the project and skips ignored files. Problems occur when classes live somewhere it does not scan. Typical cases:
- A component library installed in
node_modulesthat contains Tailwind classes. - A file listed in
.gitignorethat you still want scanned. - A separate directory outside the project root, such as a shared package in a monorepo.
Register extra locations with the @source directive in your CSS entry file.
@import "tailwindcss";
@source "../node_modules/@my-company/ui-kit";
@source "../../shared/components";The paths are relative to the CSS file. If you used Tailwind v3, the equivalent was the content array in tailwind.config.js, and files not listed there were not scanned at all. The idea is the same, but v4 detects most sources for you.
Safelisting classes that never appear in source
When class names come from a database or a content management system, they exist only at runtime. You can force Tailwind to generate them with @source inline().
@import "tailwindcss";
@source inline("bg-red-500 bg-green-500 bg-blue-500");Brace expansion keeps long lists short. The following generates every listed color at shades 100 and 500.
@import "tailwindcss";
@source inline("bg-{red,green,blue}-{100,500}");Use this sparingly. Every safelisted class adds CSS whether or not a page uses it. A lookup object in your code is almost always cleaner than a safelist.
Debugging a missing style
When a class has no effect, work through these checks in order:
- Search for the literal string. If the exact class name is not in any file, build it in full.
- Check the file is scanned. Is it in
.gitignore, innode_modules, or outside the project? Add an@sourceline. - Check the spelling.
text-slate-600exists, buttext-slate-650does not unless you defined it. A typo is silently ignored. - Rebuild or restart the dev server. Newly added
@sourcepaths may need a restart to take effect. - Inspect the output CSS. Search the generated stylesheet for the class. If it is missing, detection failed. If it is present, the problem is specificity or a conflicting rule.
Summary of rules
- Tailwind scans files as text and never executes your code.
- Every class name must appear in full, exactly as it will be used.
- Map props and data to complete class strings with a lookup object.
- Use inline styles or CSS variables for values that are only known at runtime.
- Use
@sourcefor files the scanner skips, and@source inline()only for classes that never appear in source.
Exercise
A component contains const cls = border-${tone}-500; where tone is 'red' or 'blue'. The border has no color in production. Explain why, then rewrite the code so it works.
Show answer
Tailwind scans the source as plain text and never runs the code. It sees only the fragments border- and -500, not border-red-500 or border-blue-500, so it generates no CSS for them. The fix is to write the full names in a lookup object: const tones = { red: 'border-red-500', blue: 'border-blue-500' }; const cls = tones[tone];. Both complete class names now appear literally in the file, so Tailwind generates them.
Exercise
A progress bar must show any width from 0% to 100% taken from an API value. Why is a class per percentage a poor choice, and what pattern should you use instead?
Show answer
A class per percentage would need 101 names written out or safelisted, which adds a lot of unused CSS and is clumsy to maintain. Instead, keep one static class that reads a CSS variable, such as w-[var(--progress)], and set the variable at runtime with style="--progress: 65%". Tailwind generates the single utility once, and the data controls only the value.
Exercise
You installed a UI package from npm whose components use Tailwind classes, but none of those styles show up in your app. What is the likely cause and the fix?
Show answer
The scanner skips node_modules by default, so classes used inside the package are never detected. Add the package's path to your CSS entry file with @source, for example @source "../node_modules/@my-company/ui-kit";, then restart the dev server.