0PricingLogin
Tailwind CSS Academy · Lesson

Creating Reusable Component Classes

Use @apply to build .btn, .card, and .badge classes in a global CSS file, reducing duplication in HTML templates.

Component Classes vs Utility Classes

Tailwind encourages utility-first — applying single-purpose classes directly to HTML. But for complex components like buttons, cards, and badges that appear throughout a project, extracting them into component classes with @apply reduces repetition and creates a consistent, named vocabulary for your team. The goal is not to recreate traditional CSS but to create a small set of high-value abstractions where duplication is genuinely costly.

Creating a Button Component Class

A button is one of the best candidates for a component class because every interactive UI has many buttons with the same core styles. Define a base .btn class for shared structure, then create modifier classes like .btn-primary, .btn-secondary, and .btn-outline for variants. Users apply both classes to get the full button style without knowing the underlying utilities.

@layer components {
  .btn {
    @apply inline-flex items-center justify-center gap-2
           px-4 py-2 rounded-lg text-sm font-semibold
           transition-all duration-150
           focus:outline-none focus:ring-2 focus:ring-offset-2
           disabled:opacity-50 disabled:cursor-not-allowed;
  }

  .btn-primary {
    @apply btn bg-blue-600 text-white
           hover:bg-blue-700 active:bg-blue-800
           focus:ring-blue-500;
  }

  .btn-outline {
    @apply btn border border-gray-300 text-gray-700 bg-white
           hover:bg-gray-50 active:bg-gray-100
           focus:ring-gray-400;
  }
}

All lessons in this course

  1. What @apply Does and When to Use It
  2. Creating Reusable Component Classes
  3. Organizing Custom CSS With Layers
  4. @apply Pitfalls and Alternatives
← Back to Tailwind CSS Academy