Back to roadmaps tailwind Course

Reusability with the @apply Directive

One of the most common complaints about Tailwind CSS is that writing multiple utility classes inside your HTML can make markup verbose. The @apply directive allows you to bundle these classes into custom CSS declarations.


1. What is the @apply Directive?

The @apply directive is a custom CSS rule provided by Tailwind. It tells the compiler to copy the styles of specified utility classes and paste them directly into a custom CSS class name rule:

/* src/styles/globals.css */
@layer components {
  .btn-primary {
    @apply bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded transition;
  }
}

Now, instead of duplicating nine classes on every button instance in your HTML, you can use the single class name:

<button className="btn-primary">Submit Details</button>

2. Using Layers (@layer)

When defining custom CSS rules using @apply, it is best to wrap them inside a @layer directive (typically @layer components or @layer utilities).

This ensures that:

  • Your custom styles are organized correctly in the final compiled stylesheet output.
  • Class sorting rules and override behaviors function as expected.
  • Unused classes are purged correctly during production optimization builds.

3. Pros and Cons of using @apply

While @apply looks like a clean way to reduce HTML clutter, using it too frequently can undermine the benefits of Tailwind CSS:

Pros

  • Cleaner HTML: Simplifies long class list strings for developers who prefer traditional markup.
  • Global Consistency: Centralizes styling for global interactive elements (like form inputs or tables).

Cons (The Downside)

  • Increases CSS Bundle Size: Every time you declare a custom class and use @apply, the compiler outputs new CSS properties, making the stylesheet larger.
  • Loss of Local Context: You lose the ability to see and adjust styling directly inside your HTML or React components, returning to the old stylesheet maintenance workflow.
  • Naming Overhead: You have to invent class names again, which defeats one of the core benefits of Tailwind CSS.
Published on Last updated: