Tailwind CSS Best Practices for Modern Web

Styling

Tailwind CSS has revolutionized how we style web applications. Here are best practices to follow when working with Tailwind.

Use Semantic Color Names

Tailwind provides semantic color scales that work great for most use cases:

<div class="bg-blue-500 text-white p-4">
  This is a blue button
</div>

Stick to the default palette unless you have a specific brand color scheme.

Keep Classes Organized

Group related classes together:

<!-- Good -->
<div class="flex items-center justify-between p-4 bg-white rounded-lg shadow">
  Content
</div>

<!-- Avoid mixing unrelated classes -->
<div class="p-4 flex bg-white rounded items-center shadow">
  Content
</div>

Extract Reusable Components

Don’t repeat the same class combinations:

---
const Button = (props) => (
  <button
    class={`px-4 py-2 rounded-lg font-medium transition-colors ${
      props.primary
        ? 'bg-blue-600 text-white hover:bg-blue-700'
        : 'bg-gray-200 text-gray-800 hover:bg-gray-300'
    }`}
  >
    {props.children}
  </button>
);
---

Use Dark Mode Responsibly

Implement dark mode that respects system preferences:

if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  document.documentElement.classList.add('dark');
}

Mobile-First Approach

Start with mobile styles, then add breakpoints:

<div class="p-4 md:p-8 lg:p-12">
  Content with responsive padding
</div>

Conclusion

Following these best practices will help you build maintainable and scalable Tailwind CSS projects. Focus on consistency and reusability.