Reusing Styles & Components
The most common worry about Tailwind is repetition: "If ten buttons need the same twelve classes, do I copy them ten times?" No. This lesson shows the tools Tailwind's authors recommend, in order of preference.
| Situation | Best tool |
|---|---|
| The same element repeated in a list | a loop in your template or JavaScript |
| Repetition within one small spot | multi-cursor editing — it's fine to leave it |
| A UI piece used across pages | a component (React, Vue, Svelte, a template partial …) |
| HTML you don't control, or a tiny primitive | a CSS class with @apply |
| A value used in many classes | a theme variable |
1. Loops
Most repetition comes from rendering data. Write the markup once and loop:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4.1.11"></script>
</head>
<body class="bg-slate-100 p-4">
<ul id="list" class="grid grid-cols-3 gap-3"></ul>
<script>
const planets = [['🪐', 'Saturn', '83 moons'], ['🔴', 'Mars', '2 moons'], ['🌍', 'Earth', '1 moon']];
document.getElementById('list').innerHTML = planets.map(([icon, name, moons]) => `
<li class="rounded-xl bg-white p-4 text-center shadow-sm ring-1 ring-slate-200">
<div class="text-4xl">${icon}</div>
<p class="mt-2 font-semibold text-slate-900">${name}</p>
<p class="text-sm text-slate-500">${moons}</p>
</li>`).join('');
</script>
</body>
</html>The class list appears once in the source, no matter how many planets there are.
2. Components
In a framework, extract the repeated markup into a component. The classes live in one file; every usage is short:
function Badge({ color = 'sky', children }) {
const colors = {
sky: 'bg-sky-100 text-sky-800 ring-sky-600/20',
rose: 'bg-rose-100 text-rose-800 ring-rose-600/20',
};
return (
<span className={`inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset ${colors[color]}`}>
{children}
</span>
);
}
// usage
<Badge color="rose">Overdue</Badge>Here is the same idea in plain JavaScript, so you can run it:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4.1.11"></script>
</head>
<body class="space-x-2 p-6" id="out">
<script type="module">
const variants = {
sky: 'bg-sky-100 text-sky-800 ring-sky-600/20',
rose: 'bg-rose-100 text-rose-800 ring-rose-600/20',
lime: 'bg-lime-100 text-lime-800 ring-lime-600/20',
};
function badge(text, color = 'sky') {
return `<span class="inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium ring-1 ring-inset ${variants[color]}">${text}</span>`;
}
document.getElementById('out').innerHTML =
badge('Draft') + badge('Overdue', 'rose') + badge('Paid', 'lime') + badge('In review');
</script>
</body>
</html>Never build class names from pieces
Tailwind finds classes by scanning your source files as plain text. It never runs your code, so it can't see a class that only exists after string concatenation:
// ❌ Tailwind never sees "bg-rose-100" — the class won't exist
const cls = `bg-${color}-100`;
// ✅ Write complete class names so the scanner can find them
const map = { rose: 'bg-rose-100', sky: 'bg-sky-100' };
const cls = map[color];That's why the variants object above lists full class names for each colour. (The browser build used in these playgrounds reads the live page, so it is more forgiving — but a real Vite or CLI build is not.)
Note: If you genuinely need classes that appear nowhere in your source (e.g. they come from a database), safelist them with
@source inline("bg-rose-100 bg-sky-100")in v4.
3. Conditional classes
Toggle classes based on state with a tiny helper. Libraries like clsx do this, but the idea is simple:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4.1.11"></script>
</head>
<body class="p-6">
<div id="tabs" class="inline-flex gap-1 rounded-xl bg-gray-100 p-1"></div>
<script type="module">
const cx = (...parts) => parts.filter(Boolean).join(' ');
let active = 'Week';
function render() {
document.getElementById('tabs').innerHTML = ['Day', 'Week', 'Month'].map(t => `
<button data-t="${t}" class="${cx(
'rounded-lg px-4 py-1.5 text-sm font-medium transition',
t === active ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-500 hover:text-gray-800'
)}">${t}</button>`).join('');
}
document.getElementById('tabs').addEventListener('click', e => {
if (e.target.dataset.t) { active = e.target.dataset.t; render(); }
});
render();
</script>
</body>
</html>4. @apply for small primitives
When there is no template layer (for instance, Markdown rendered by a CMS) a CSS class is the right tool:
@layer components {
.btn-primary {
@apply rounded-lg bg-indigo-600 px-4 py-2 font-semibold text-white hover:bg-indigo-500;
}
}Keep these few and small. Overusing @apply recreates the naming problems Tailwind was designed to avoid.
Keeping long class lists tidy
| Habit | Why |
|---|---|
Use the official Prettier plugin prettier-plugin-tailwindcss |
sorts classes in a consistent order automatically |
| Group by concern when writing by hand: layout → box → typography → colour → states | easier to scan |
Use size-*, inset-*, px-*/py-* shorthands |
fewer classes |
Let a library like tailwind-merge resolve conflicts in reusable components |
p-2 passed in overrides p-4 reliably |
Tip: Long class lists in one place are not a problem — they're explicit and local. Copy-pasted lists in many places are the real smell, and components fix that.
Test yourself
Why does ` text-${color}-600 ` fail to produce styles?
- Template literals are not allowed in HTML
- Tailwind scans files as text and never sees the complete class name
- Tailwind only supports
text-black - It needs
@apply
What is the recommended first choice for a button style used on many pages of a React app?
- Copy the classes everywhere
- A
Buttoncomponent - An inline
styleattribute - A
!importantclass
What does prettier-plugin-tailwindcss do?
- Removes unused classes
- Sorts class names into a consistent order
- Converts classes to CSS
- Adds dark mode classes