Tailwind CSS has transformed how developers approach styling. Instead of writing custom CSS, you compose designs using utility classes. Let's explore how to build beautiful UIs with Tailwind.
Why Tailwind CSS?
Tailwind offers several advantages:
- Rapid Development: Style directly in your HTML/JSX
- Consistency: Built-in design system with spacing, colors, etc.
- No Context Switching: Stay in your component files
- Small Bundle Size: Only includes classes you use
Getting Started
After installing Tailwind, you can start styling immediately:
<button class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded">
Click me
</button>
Building Components
Cards
Create elegant cards with shadows and rounded corners:
<div class="bg-white rounded-2xl shadow-lg p-6 hover:shadow-xl transition-shadow">
<h3 class="text-xl font-bold mb-2">Card Title</h3>
<p class="text-gray-600">Card content goes here.</p>
</div>
Buttons
Build a button system with variants:
<!-- Primary -->
<button class="bg-indigo-600 text-white px-6 py-3 rounded-lg hover:bg-indigo-700">
Primary
</button>
<!-- Secondary -->
<button class="border-2 border-indigo-600 text-indigo-600 px-6 py-3 rounded-lg hover:bg-indigo-50">
Secondary
</button>
Responsive Design
Tailwind makes responsive design intuitive:
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<!-- Items stack on mobile, 2 columns on tablet, 3 on desktop -->
</div>
The breakpoint prefixes are:
sm: 640px and upmd: 768px and uplg: 1024px and upxl: 1280px and up
Dark Mode
Enable dark mode with the dark: prefix:
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
This adapts to the user's theme preference
</div>
Animation & Transitions
Add polish with smooth transitions:
<button class="transform hover:scale-105 transition-all duration-200 ease-out">
Hover me
</button>
Best Practices
1. Extract Components
When patterns repeat, create components:
function Button({ children, variant = 'primary' }) {
const styles = {
primary: 'bg-indigo-600 text-white hover:bg-indigo-700',
secondary: 'border-2 border-indigo-600 text-indigo-600 hover:bg-indigo-50'
};
return (
<button className={`px-6 py-3 rounded-lg transition-colors ${styles[variant]}`}>
{children}
</button>
);
}
2. Use CSS Variables
Combine Tailwind with CSS variables for theming:
:root {
--primary: #6366f1;
}
.btn-primary {
background-color: var(--primary);
}
3. Organize Long Class Lists
Break up long class strings for readability:
const cardClasses = [
'bg-white rounded-2xl shadow-lg',
'p-6 hover:shadow-xl',
'transition-all duration-200'
].join(' ');
Conclusion
Tailwind CSS empowers you to build beautiful, responsive interfaces quickly. Its utility-first approach might feel different at first, but once you embrace it, you'll find yourself building UIs faster than ever.
Happy styling!