Tailwind CSS CSS Best Practices
Tailwind CSS Best Practices for 2024
Discover the best practices for using Tailwind CSS effectively in your projects, from organization to performance optimization.
Michael Torres •
Introduction
Tailwind CSS has revolutionized how we write CSS. But with great power comes great responsibility. Let’s explore the best practices for using Tailwind effectively.
1. Use Component Extraction
Instead of repeating utility classes, extract them into components:
// Before
<button class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
Click me
</button>
// After - Create a Button component
<Button variant="primary">Click me</Button>
2. Leverage @apply Sparingly
While @apply is useful, overusing it defeats the purpose of utility-first CSS:
/* Good - for truly reusable patterns */
.btn-primary {
@apply px-4 py-2 bg-blue-500 text-white rounded;
}
/* Avoid - too specific */
.hero-title {
@apply text-4xl font-bold text-gray-900 mb-4;
}
3. Organize with Plugins
Create custom plugins for repeated patterns:
// tailwind.config.js
module.exports = {
plugins: [
function({ addComponents }) {
addComponents({
'.card': {
padding: '1rem',
borderRadius: '0.5rem',
backgroundColor: 'white',
boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
},
});
},
],
};
4. Use CSS Variables for Theming
Combine Tailwind with CSS variables for dynamic theming:
:root {
--color-primary: 99 102 241;
}
.dark {
--color-primary: 129 140 248;
}
5. Purge Unused Styles
Always configure content paths correctly:
module.exports = {
content: [
'./src/**/*.{astro,html,js,jsx,ts,tsx}',
],
};
Conclusion
Following these best practices will help you write maintainable, performant Tailwind CSS code. Remember: the goal is to be productive while keeping your codebase clean.