Course contentsShow
← React
Lesson 1919 of 2,39644. Styling ApproachesFree lesson

The @apply Directive: When and Why

Using @apply in CSS files to compose utilities into semantic class names, and when this pattern is appropriate.

The @apply Directive: When and Why

What you'll learn: How to use Tailwind's @apply directive to compose utility classes into semantic CSS classes, and when this approach actually makes sense.

What @apply Does

The @apply directive lets you extract repeating utility combinations into traditional CSS class names. Instead of writing className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded" everywhere, you can create a .btn-primary class that applies those utilities:

/* styles.css */
.btn-primary {
  @apply flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded;
}

Then use it like any CSS class:

<button className="btn-primary">
  Click me
</button>

When to Use @apply

Think of @apply as a bridge between utility-first and component-based styling. Use it when:

  • Integrating with legacy CSS files that expect semantic class names
  • Creating base styles for elements you don't control (like markdown content)
  • Truly repeated patterns that appear across many components and resist React component extraction

When NOT to Use @apply

Don't reach for @apply just because utility classes look "messy." If you're extracting patterns like buttons, cards, or form inputs, create React components instead:

// Better: React component
function PrimaryButton({ children }) {
  return (
    <button className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded">
      {children}
    </button>
  );
}

This keeps your styles co-located, allows props for variations, and maintains the utility-first philosophy where you can see all styles at the usage site.

Key Takeaway: Use @apply sparingly for legacy CSS integration or truly global patterns—prefer React components for extracting reusable UI elements, as this keeps your styling declarative and visible where it's used.