Tailwind CSS has revolutionized how we style web applications. Let's dive deep into this utility-first framework.
Why Tailwind CSS?
Traditional CSS has pain points: naming things is hard, CSS files grow large, and maintaining consistency across teams is difficult. Tailwind solves these by providing pre-built utility classes.
Getting Started
Install Tailwind via npm:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -pConfigure your tailwind.config.js:
module.exports = {
content: ["./src/**/*.{html,js}"],
theme: {
extend: {},
},
plugins: [],
}Core Concepts
Utility Classes
Every utility class maps to a single CSS property:
p-4→padding: 1rem;text-lg→font-size: 1.125rem;bg-blue-500→background-color: #3b82f6;
Responsive Design
Breakpoints are mobile-first:
sm: 640pxmd: 768pxlg: 1024pxxl: 1280px2xl: 1536px
Example:
<div class="w-full md:w-1/2 lg:w-1/3">
Responsive width
</div>Hover, Focus, and States
<button class="bg-blue-500 hover:bg-blue-700 focus:ring-2">
Click me
</button>Advanced Techniques
Custom Configuration
Extend the theme in tailwind.config.js:
theme: {
extend: {
colors: {
brand: '#3b82f6',
},
spacing: {
'128': '32rem',
}
}
}Component Classes with @apply
.btn {
@apply px-4 py-2 bg-blue-500 text-white rounded;
}Dark Mode
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
Dark mode support
</div>Best Practices
- 1Extract Components: Don't repeat utility combinations
- 2Use JIT Mode: Faster build times with Just-In-Time compiler
- 3Purge Unused Styles: Keep bundle size small
- 4Consistent Spacing: Use the spacing scale consistently
- 5Group Related Utilities: Keep readable class order
Tailwind UI Plugins
Enhance Tailwind with:
- @tailwindcss/forms: Better form styling
- @tailwindcss/typography: Beautiful prose styling
- @tailwindcss/aspect-ratio: Aspect ratio utilities
Performance
Tailwind is production-ready:
- Small CSS bundle with purging
- No runtime overhead
- Tree-shakeable
- Critical CSS extraction
Conclusion
Tailwind CSS speeds up development, ensures consistency, and reduces bundle size. Start with the basics, adopt advanced patterns as needed, and build beautiful interfaces faster.