Tailwind CSS Overview
Tailwind CSS, a minimal, practical, and highly customizable CSS framework, differs from traditional UI frameworks by providing semantic utility classes instead of prebuilt components. By composing these classes, developers can rapidly build visually appealing interfaces.
Installation
Add Tailwind CSS to your project by running these commands in your project root:
npm install -D tailwindcss
npx tailwindcss init
This installs Tailwind and generates the default configuration file:
/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{html,js}'],
theme: {
extend: {},
},
plugins: [],
}
You're now ready to style elements with Tailwind's utility classes.
Basic Usage
Style buttons with different background colors:
<button class="bg-blue-300 px-4 py-2 rounded">Primary</button>
<button class="bg-red-100 px-4 py-2 rounded">Warning</button>
<button class="bg-yellow-500 px-4 py-2 rounded">Highlight</button>
Enhance with additional utilities:
<button class="border border-gray-400 rounded-lg bg-blue-500 text-white px-4 py-2">
Styled Button
</button>
For comprehensive class references, see the official documentation.
Common Issues & Solutions
1. Preflight Resets Default Styles
Tailwind's Preflight (based on modern-normalize) resets default browser styles:
/* Default Preflight behavior */
h1, h2, h3, h4, h5, h6 {
font-size: inherit;
font-weight: inherit;
}
Solution: Disable Preflight in your config file:
// tailwind.config.js
module.exports = {
corePlugins: {
preflight: false, // Disables default style reset
}
};
2. Styles Not Applying?
Ensure your template paths are correctly configured:
export default {
content: [
'./src/**/*.{html,js,jsx,ts,tsx}', // Add all relevant file extensions
],
}
3. Purge Unused Styles for Production
Add purge configuration for optimal performance:
export default {
purge: ['./src/**/*.{html,js}'], // Tree-shakes unused styles
}
Pro Tip: Use
@apply
to create custom component classes when utility combinations become repetitive:
.btn-primary { @apply px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600; }
For advanced customization, explore the Theme Configuration documentation.