Tailwind CSS Best Practices
Published on
by Nguyễn Công Dũngtailwindcssresponsivetutorial
Tailwind CSS Best Practices
Tailwind CSS is a utility-first CSS framework that allows you to build modern designs quickly. Here are some best practices to keep your Tailwind code maintainable and efficient.
Component Extraction
Don’t repeat long class strings. Extract them into components:
// ❌ Bad
<button className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
Click me
</button>
// ✅ Good
function Button({ children, ...props }) {
return (
<button
className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
{...props}
>
{children}
</button>
);
}Use @apply for Repeated Patterns
For truly repeated patterns, use @apply:
.btn-primary {
@apply px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors;
}Responsive Design
Use responsive prefixes consistently:
<div className="
text-sm md:text-base lg:text-lg
p-4 md:p-6 lg:p-8
">
Content
</div>Dark Mode
Leverage dark mode utilities:
<div className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
Content
</div>Custom Configuration
Extend Tailwind config for project-specific values:
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
brand: {
50: '#f0f9ff',
500: '#0ea5e9',
900: '#0c4a6e',
},
},
},
},
};Performance Tips
- Purge unused styles: Ensure
contentpaths are correct - Avoid arbitrary values: Use theme values when possible
- Group related utilities: Keep related classes together
- Use JIT mode: Enable Just-In-Time compilation for faster builds
Common Patterns
Card Component
<div className="bg-white rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow">
{content}
</div>Container
<div className="container mx-auto px-4 max-w-7xl">
{content}
</div>Flexbox Centering
<div className="flex items-center justify-center min-h-screen">
{content}
</div>Happy styling!