Tailwind CSS Best Practices
TeD··4 min read
#tailwind#css#styling
Tailwind CSS Best Practices
Tailwind CSS is a utility-first CSS framework that helps you build modern websites quickly. However, to get the most out of it, you need to follow some best practices.
Key Principles
1. Use @apply Sparingly
While @apply is convenient, overusing it defeats the purpose of utility-first CSS. Use it only for frequently repeated patterns.
/* Good - used for a common pattern */
.btn-primary {
@apply px-4 py-2 bg-blue-500 text-white rounded;
}
2. Organize with Components
Break your UI into reusable components rather than repeating utility classes.
function Button({ children }) {
return (
<button className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
{children}
</button>
);
}
3. Leverage the Configuration File
Customize Tailwind to match your design system:
module.exports = {
theme: {
extend: {
colors: {
brand: '#0070f3',
},
},
},
}
Example
Here's a practical example of well-structured Tailwind code:
<div className="flex items-center justify-between p-4 bg-white rounded-lg shadow-md">
<h2 className="text-xl font-bold">Hello World</h2>
<button className="px-3 py-1 text-sm bg-blue-500 text-white rounded">
Click me
</button>
</div>
Performance Tips
- Use PurgeCSS (built into Tailwind)
- Keep utility classes organized
- Use component extraction for complex patterns
Conclusion
Following these best practices will help you maintain clean and efficient Tailwind CSS code. Your projects will be more maintainable and your team will thank you!