Back to posts

Tailwind CSS Best Practices

Published on
by Nguyễn Công Dũng
tailwindcssresponsivetutorial

Tailwind CSS Best Practices

Tailwind CSS is a utility-first CSS framework that allows you to build modern designs quickly. Here are some best practices to keep your Tailwind code maintainable and efficient.

Component Extraction

Don’t repeat long class strings. Extract them into components:

React
// ❌ Bad
<button className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
  Click me
</button>
 
// ✅ Good
function Button({ children, ...props }) {
  return (
    <button
      className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
      {...props}
    >
      {children}
    </button>
  );
}

Use @apply for Repeated Patterns

For truly repeated patterns, use @apply:

CSS
.btn-primary {
  @apply px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors;
}

Responsive Design

Use responsive prefixes consistently:

React
<div className="
  text-sm md:text-base lg:text-lg
  p-4 md:p-6 lg:p-8
">
  Content
</div>

Dark Mode

Leverage dark mode utilities:

React
<div className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white">
  Content
</div>

Custom Configuration

Extend Tailwind config for project-specific values:

JavaScript
// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      colors: {
        brand: {
          50: '#f0f9ff',
          500: '#0ea5e9',
          900: '#0c4a6e',
        },
      },
    },
  },
};

Performance Tips

  1. Purge unused styles: Ensure content paths are correct
  2. Avoid arbitrary values: Use theme values when possible
  3. Group related utilities: Keep related classes together
  4. Use JIT mode: Enable Just-In-Time compilation for faster builds

Common Patterns

Card Component

React
<div className="bg-white rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow">
  {content}
</div>

Container

React
<div className="container mx-auto px-4 max-w-7xl">
  {content}
</div>

Flexbox Centering

React
<div className="flex items-center justify-center min-h-screen">
  {content}
</div>

Happy styling!