Reusing Styles in Tailwind CSS
When moving from traditional CSS to Tailwind, your first instinct is often to "clean up" your HTML by extracting groups of utility classes into a single, abstract CSS class.
This is a natural reflex driven by the DRY (Don't Repeat Yourself) principle. In traditional CSS, if you have five buttons with the same padding, color, and border-radius, you create a .btn class so you only have to maintain those styles in one place. However, in a utility-first workflow, premature abstraction can lead to the very same maintenance headaches that Tailwind was designed to solve, such as large, complex CSS files and "CSS append-only" syndrome.
Instead of creating abstract CSS classes, Tailwind encourages you to reuse styles through your templating language or frontend framework.
Loops & Mapping
If you have a list of similar items (like a navigation menu or a list of cards), you shouldn't manually repeat the utility classes. Instead, use a loop to render the elements.
The Problem
Repeating the same classes multiple times is tedious and hard to maintain:
The Solution
By using a loop, you define the styling once. If you want to change the hover color from bg-slate-100 to bg-blue-100, you only have to edit one line of code.
Using @apply
If you absolutely must extract common utility patterns into a single CSS class (e.g., for very large projects where component-based reuse isn't sufficient), Tailwind provides the @apply directive.
For this to work, your external CSS file must be processed by Tailwind. This is typically done by including the Tailwind directives at the top of your main CSS file:
Component Abstraction
The highly recommended way to reuse styles in Tailwind is through component abstraction. If you find yourself repeating a complex UI pattern, extract it into a reusable template or component in your framework of choice (like a Button component or a Card partial).
In the next page, we'll see how to customize Tailwind's default theme to match your specific design requirements.