While
@apply
can be useful for abstracting common utility combinations, it's important not to overuse it. This example illustrates the potential pitfalls.
Consider this card, styled directly with Tailwind utilities:
Styled with many utility classes!
Utilities used:
p-6 max-w-md mx-auto bg-white rounded-xl shadow-lg flex items-center space-x-4 border border-gray-200 ...
Seeing all those utility classes, one might be tempted to create a single custom class like
.custom-card
using
@apply
.
/* In CSS (conceptual): */
.custom-card {
@apply p-6 max-w-md mx-auto bg-white rounded-xl shadow-lg flex items-center space-x-4 border border-gray-200;
/* ... potentially more classes ... */
}
<div class="custom-card">
in your HTML, you can no longer see the specific Tailwind utilities at a glance. Debugging or modifying styles requires jumping to the CSS file, losing the immediate context Tailwind provides.
@apply
can recreate the problems utility-first CSS aims to solve, such as having large, abstract CSS classes that are hard to manage, override, or reason about without constantly checking their definitions.
.custom-card
, it becomes less flexible than composing utilities directly in HTML.
@apply
usage.
Guidance:
Use
@apply
sparingly, for very small, highly-reused utility patterns (e.g., a specific text style focus ring, or a very simple button base), rather than for entire component abstractions.