Sub topic 14
Reusing styles with components and @apply
This chapter assumes you know the basics from earlier chapters: utility classes in markup, responsive and state variants, dark mode, how Tailwind detects classes, and the @theme block. Here you will learn how to avoid repeating long class lists without giving up the benefits of utilities.
Why repetition feels like a problem
A utility-first style puts many classes on one element. A primary button might look like this:
<button class="rounded-lg bg-indigo-600 px-4 py-2 text-white hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500">
Save
</button>If the same button appears in twelve places, you now have twelve copies of that string. Changing the hover color means editing twelve places, and you can easily miss one.
The cause is duplicated source, not utilities themselves. The fix is to define the thing once. Tailwind offers several ways to do that. Which one fits depends on where the duplication lives.
Decide what kind of repetition you have
Not all repetition needs a fix. Ask these questions first:
- Is the same markup repeated inside one file, such as list items? Use a loop.
- Is the same markup and style repeated across files? Use a component or template partial.
- Is only a class string repeated, on elements that have no shared markup, or in a place where you cannot use a component? Consider
@applyor a plain CSS class. - Is a single value, such as a brand color, repeated? Use a design token in
@theme.
The table summarizes the options.
| Technique | Best for | Main cost |
|---|---|---|
| Loop | Repeated items in one template | None, limited to one place |
| Component or partial | Repeated markup with styling | Needs a framework or template system |
| `@apply` custom class | Repeated class strings without markup control | Adds a second place to look for styles |
| Theme token | Repeated values such as colors | Applies to values, not whole patterns |
Loops
If the repetition is a list, you do not need any abstraction. Write the markup once and render it many times. The class string then exists in one place.
const links = [
{ href: '/docs', label: 'Docs' },
{ href: '/blog', label: 'Blog' },
{ href: '/about', label: 'About' },
];
const html = links
.map(
(link) =>
`<li><a href="${link.href}" class="rounded px-3 py-2 text-slate-700 hover:bg-slate-100">${link.label}</a></li>`
)
.join('\n');
console.log(html);Notice that the full class names appear literally in the source. This keeps them detectable by Tailwind's scanner, as covered in the chapter on dynamic class names.
Components
When the same markup and styling appear in many files, wrap them in a component. A component is a reusable unit in your framework or template engine, such as a React component, a Vue single-file component, or a server-side partial.
This is the approach Tailwind recommends first. The component holds both the structure and the classes, so one edit updates every use.
function Button({ children, variant = 'primary' }) {
const variants = {
primary: 'bg-indigo-600 text-white hover:bg-indigo-700 focus:ring-indigo-500',
secondary: 'bg-slate-200 text-slate-900 hover:bg-slate-300 focus:ring-slate-400',
};
return `<button class="rounded-lg px-4 py-2 focus:ring-2 ${variants[variant]}">${children}</button>`;
}
console.log(Button({ children: 'Save' }));
console.log(Button({ children: 'Cancel', variant: 'secondary' }));Two details matter here:
- The shared classes (
rounded-lg px-4 py-2 focus:ring-2) sit in the base string. Only the parts that differ live in each variant. - Each variant is a complete literal string in a lookup object. This is the safe pattern from the dynamic classes chapter. Writing `
bg-${color}-600` instead would hide the class from the scanner.
A component also gives you a place to accept props, handle accessibility attributes, and keep behavior next to style. A CSS class cannot do any of that.
Customizing a component from outside
A common edge case is a caller who needs to adjust one thing, such as extra margin. If the component simply appends a className prop to its base classes, conflicting utilities can fight. For example, px-4 in the base and px-8 from the caller are both present. The one that wins depends on the order of rules in the generated stylesheet, not the order in the class attribute.
To avoid this, either:
- Limit what callers can override and expose variants instead.
- Use a merge helper from your ecosystem (such as
tailwind-merge) that removes the losing class when two utilities conflict. - Let the caller control only layout concerns, like margin, and keep the component in charge of padding and color.
Using @apply
Sometimes a component is not practical. You may be styling markup you do not control, such as HTML rendered from Markdown or a third-party widget. Or you may be working in plain HTML with no template system. In these cases you can write a CSS class and inline utilities into it with @apply.
@import "tailwindcss";
.btn-primary {
@apply rounded-lg bg-indigo-600 px-4 py-2 text-white hover:bg-indigo-700;
}You then use the class in markup:
<button class="btn-primary">Save</button>@apply copies the CSS declarations of those utilities into .btn-primary. Variants such as hover: work inside it, and the output includes the matching :hover rule.
How it works internally
@apply is a build-time directive. Tailwind replaces it with the declarations that the named utilities would produce. The result is ordinary CSS, and the @apply line does not appear in the output.
Rather than a diagram of that, here is the sequence in a diagram you can follow:
Because the class is generated from your stylesheet, it is always included in the output. It does not depend on the scanner finding the name in your source files, though the HTML still has to use it to have any effect.
Gotchas with @apply
- Specificity and order. A custom class is a single class selector, the same specificity as a utility. If you add
class="btn-primary px-8", the result depends on which rule comes later in the stylesheet. Do not assume the utility in the markup wins. - Duplicated declarations. Each
@applycopies CSS. Using it on many classes increases the stylesheet size, where reusing utilities in markup does not. - Hidden styling. A reader sees
btn-primaryin the HTML and must open the CSS file to learn what it does. You lose the main advantage of utility-first, which is reading the styles in place. - Separate stylesheets. In Tailwind v4, a CSS file that is not the main one, such as a CSS module or a Vue
<style>block, does not automatically know about your theme. You need to reference the main stylesheet there, for example with@reference "../app.css";, before@applycan resolve your utilities and tokens. - Growing a second framework. If you find yourself writing
@applyclasses for most elements, you have rebuilt traditional CSS with extra steps.
Design tokens come first
Before extracting a pattern, check whether the repeated part is really a value. If bg-indigo-600 is your brand color everywhere, name it once:
@import "tailwindcss";
@theme {
--color-brand: #4f46e5;
}Now bg-brand, text-brand, and border-brand all exist. Changing the brand color is a one-line edit. Tokens solve repeated values without hiding any structure, so they pair well with components.
Choosing between the options
Use this order of preference:
- Remove duplication with a loop if it is within one template.
- Extract a component if markup and style repeat across files.
- Move repeated values into theme tokens.
- Use
@applyonly when you cannot use a component, such as content you do not control, or when you need a class that other CSS or JavaScript must target.
Do not extract too early. A pattern used twice might diverge next week. Copying a class list twice is cheap. A wrong abstraction costs more, because every variation becomes a new prop or flag. Wait until the third use, and extract when the pieces clearly belong together.
Common mistakes
- Building variant class names from fragments, such as
bg-${variant}-600, inside a component. Use a lookup object of full class names. - Using
@applyin a separate stylesheet without referencing the main one, and getting an error about an unknown utility. - Appending a caller's
classNamewithout handling conflicts, and getting a result that depends on stylesheet order. - Creating one-use
@applyclasses, which add indirection with no reuse. - Extracting a component too early, then adding many props to cover cases that differ.
Exercise
A team has a Card component that always applies p-6. A page needs a card with less padding, so the developer passes className="p-2", but the card still shows p-6 in some builds. Why does this happen, and what are two ways to fix it?
Show answer
Both p-6 and p-2 are on the element, and Tailwind decides the winner by the order of rules in the generated stylesheet, not by the order in the class attribute. The result is therefore not controlled by the caller. Fixes: use a merge helper such as tailwind-merge so the conflicting p-6 is removed when p-2 is passed, or expose a variant prop (for example size="compact") that selects a full literal class string such as p-2 from a lookup object, so the component controls padding itself.
Exercise
You are styling HTML generated from Markdown, where you cannot add classes to individual elements. Which reuse technique fits, and what extra step is needed if the rule lives in a separate CSS file in Tailwind v4?
Show answer
Use a CSS rule with @apply, because a component cannot change the generated markup. In a separate CSS file in Tailwind v4, add @reference pointing at the main stylesheet so that @apply can resolve your utilities and theme tokens.