Day 3 of 5
⏱ ~60 minutes
Tailwind CSS in 5 Days — Day 3

Components and Reuse

Repeating the same 15 utility classes everywhere is unsustainable. This lesson covers extracting components, using @apply for patterns, and building a reusable component library.

The Repetition Problem

If you have 20 buttons that all need px-4 py-2 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors, you have a problem. Three solutions, in order of preference:

  1. Component abstraction — Create a Button component in your framework (React, Vue, Svelte). One place to change.
  2. @apply — Extract class lists into a named CSS class. Use sparingly.
  3. Copy-paste — Acceptable for small projects where consistency matters less.
Using @apply in CSS
/* Only do this for genuinely reused patterns */
@layer components {
  .btn {
    @apply px-4 py-2 rounded-lg font-medium transition-colors focus:outline-none focus:ring-2;
  }
  .btn-primary {
    @apply bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500;
  }
  .btn-secondary {
    @apply bg-gray-100 text-gray-900 hover:bg-gray-200 focus:ring-gray-400;
  }
  .card {
    @apply bg-white rounded-xl shadow-sm border border-gray-100 p-6;
  }
}
⚠️
Don't overuse @apply. Tailwind's creator Adam Wathan says: if you're using @apply for everything, you've lost the benefits of utility-first. Use it for truly repeated patterns (3+ instances), not as a crutch to avoid writing utilities in HTML.

Building Real Components

Button variants pattern






Notification component
...

Success!

Your changes have been saved.

💡
Tailwind's group utility enables parent-child hover states. Add group to the parent, then group-hover:text-blue-600 to the child. Hover the parent, the child changes. Perfect for cards with hover effects.
📝 Day 3 Exercise
Build a Component Library
  1. Build these components using only Tailwind: primary button, secondary button, danger button.
  2. Build an alert component in 4 variants: success (green), warning (yellow), error (red), info (blue).
  3. Build a card with an image, title, description, and a 'Read more' link.
  4. Use the group utility on the card so hovering the card highlights the title.
  5. Build a badge/tag component in 5 color variants.

Day 3 Summary

  • Extract repeated class lists into framework components, not always @apply.
  • @apply works for genuinely reused patterns — use sparingly, max once per pattern.
  • group on parent + group-hover:* on child = parent-triggered child hover effects.
  • Tailwind's layering: @layer base (elements), @layer components (classes), @layer utilities (one-off utilities).
Finished this lesson?