Best Practices
Tips for clean, maintainable Tailwind code.
A few habits keep utility-first projects tidy.
Do
- Design mobile-first: base styles, then add
md:andlg:. - Extract repeated patterns into a component (in your framework) or an
@applyclass. - Stick to the spacing and color scale for consistency.
- Use a build step for production to ship tiny CSS.
Avoid
- Reaching for arbitrary values when a scale value fits.
- Duplicating long class lists everywhere instead of componentizing.
Example
Loading editorβ¦
Press Run to see the result.
When to use it
- A developer reduces repetitive class strings by extracting a shared button pattern into a @apply component class rather than duplicating utilities in every template.
- A team avoids purging issues in production by ensuring all dynamic class names are written as complete strings in source files, not constructed with string concatenation.
- A developer keeps utility lists readable by grouping classes by concern (layout, color, typography, states) in a consistent order within each element.
More examples
Avoid dynamic class construction
Tailwind's JIT scanner looks for complete class name strings; dynamically constructed partials are invisible to the scanner and get purged from the output.
// Bad: Tailwind cannot detect partial class names at build time
const cls = `text-${color}-600`; // purged!
// Good: use complete class names
const colors = {
red: 'text-red-600',
blue: 'text-blue-600',
};
const cls = colors[color]; // safeOrdered class grouping
Grouping classes by layout, box, spacing, typography, state, and transition makes long class strings easier to scan and review.
<div
class="
flex items-center gap-4
bg-white rounded-lg shadow
p-6
text-gray-900 text-sm font-medium
hover:shadow-md
transition duration-200
"
>
Content
</div>Component extraction with @apply
Repeated card patterns are extracted into .card, .card-title, and .card-body component classes so templates stay short and changes propagate from one place.
@layer components {
.card {
@apply bg-white rounded-xl shadow p-6;
}
.card-title {
@apply text-lg font-semibold text-gray-900;
}
.card-body {
@apply text-sm text-gray-500 mt-2;
}
}
Discussion