Tailwind CSS Tutorial · Customizing Tailwind · Lesson 21 of 27

Reusing Styles

How to avoid repeating long class lists: loops, components and partials, @apply for small cases, and custom @utility classes.

Create a free account to save this page, take notes and track your progress. Sign in

1. Loops and components (the best option)

Repeated markup usually comes from data. Render it in a loop or a component, and the classes are written once:

function Button({ children, variant = "primary" }) {
  const styles = {
    primary: "bg-indigo-600 text-white hover:bg-indigo-500",
    secondary: "bg-white text-gray-900 ring-1 ring-gray-300 hover:bg-gray-50",
  };
  return <button className={`rounded-lg px-4 py-2 font-medium ${styles[variant]}`}>{children}</button>;
}

The same works with Vue components, Blade components, Django/Jinja includes and Rails partials.

2. @apply (for small, global cases)

@apply copies utilities into your own CSS class. It's handy for HTML you don't control (CMS content, third-party widgets), but don't rebuild a whole CSS framework with it:

@apply for a button classTry it yourself
<style type="text/tailwindcss">
  .btn {
    @apply rounded-lg px-4 py-2 font-medium transition;
  }
  .btn-primary {
    @apply bg-indigo-600 text-white hover:bg-indigo-500;
  }
</style>
<div class="flex gap-3 p-6">
  <button class="btn btn-primary">Save</button>
  <button class="btn bg-gray-100 hover:bg-gray-200">Cancel</button>
</div>

3. Custom utilities

@utility adds a real utility that works with every variant (hover:, md:…):

@utility content-auto {
  content-visibility: auto;
}

Merging classes

When a component accepts extra classes, conflicting utilities (p-2 and p-4) depend on CSS order, not class order. Libraries such as tailwind-merge resolve conflicts so the caller's class wins.

Test yourself

What's the recommended way to reuse a repeated button style in a React app?

  1. Make a Button component
  2. Copy the classes everywhere
  3. Use @apply for every element
  4. Use inline styles
Show answer

Answer: Make a Button component

Components keep the classes in one place and work with any framework.

Was this page helpful?