Skip to content

Tailwind CSS Reusing Styles

When you build projects with Tailwind CSS, you might find yourself repeatedly using the same combinations of utility classes to create specific UI elements, such as buttons or cards. While writing utility classes directly in HTML is the core philosophy of Tailwind, in some situations, extracting and reusing these style combinations can improve code maintainability.

Primary Method: Creating Components

This is the approach most recommended by Tailwind.

Instead of creating CSS classes like .btn, create reusable components (for example, in Vue or React). This component encapsulates all related HTML structure and Tailwind utility classes.

Example (Vue 3):

vue
<!-- components/AppButton.vue -->
<template>
  <button
    class="py-2 px-4 font-semibold rounded-lg shadow-md text-white bg-blue-500 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75"
  >
    <slot></slot>
  </button>
</template>

Then, you can reuse this button component anywhere in your application:

html
<AppButton>Click me</AppButton>
<AppButton>Submit</AppButton>

Advantages:

  • True reusability: You're not just reusing styles, but also HTML structure, JavaScript behavior, and accessibility properties.
  • No increase in CSS size: Because you're still using utility classes directly, the final generated CSS file won't grow.
  • High maintainability: When you need to modify button styles, you only need to make changes in one place (the component file).

Alternative Method: Using @apply

If you're not using a framework that supports components, or you just want to create CSS classes for some simple, repeating patterns, you can use the @apply directive.

@apply allows you to "inline" a series of Tailwind utility classes in your custom CSS classes.

Example:

In your main CSS file (e.g., src/style.css):

css
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  .btn-primary {
    @apply py-2 px-4 font-semibold rounded-lg shadow-md text-white bg-blue-500 hover:bg-blue-700;
  }
}

Then you can use this newly created class in HTML:

html
<button class="btn-primary">Click me</button>

Caveats and Disadvantages:

  • Use sparingly: Overusing @apply will take you back to the old ways of traditional CSS, potentially leading to CSS file bloat and style conflicts. Tailwind's author recommends prioritizing the component-based approach.
  • Maintainability: When a .btn-primary class is used everywhere, modifying it can have unexpected side effects, which is exactly the problem Tailwind tries to solve.
  • Only for leaf nodes: It's best to use @apply only for "ultimate" elements that won't be overridden by other classes (like buttons, form elements).

Conclusion: Prioritize reusing styles by creating components. Only consider using @apply as an alternative in the few cases where creating components is not possible or suitable.

Content is for learning and research only.