Customization and ThemingLesson 5.4
Using @apply in Tailwind to extract component classes
@apply directive, component extraction, when to use @apply, CSS layer, @layer components, base styles, @apply limitations, anti-patterns
@apply: Extracting Reusable Styles
@apply extracts repeated utility combinations into a CSS class. Use it sparingly โ most component extraction belongs in your JS framework's component system, not CSS.
Basic usage
/* src/style.css */
@layer components {
.btn-primary {
@apply inline-flex items-center justify-center px-4 py-2 rounded-md
font-medium text-sm bg-blue-600 text-white
hover:bg-blue-700 focus:outline-none focus:ring-2
focus:ring-blue-500 focus:ring-offset-2
transition-colors disabled:opacity-50 disabled:cursor-not-allowed;
}
.input-base {
@apply block w-full px-3 py-2 border border-gray-300 rounded-md
text-sm focus:outline-none focus:ring-2 focus:ring-blue-500;
}
.card {
@apply bg-white rounded-xl border border-gray-100 shadow-sm p-6;
}
}Using the extracted classes
<button class="btn-primary">Save</button>
<input class="input-base" type="text" />
<div class="card">Content</div>When NOT to use @apply
Avoid @apply for one-off elements โ it adds CSS weight without reuse benefit. In React or Vue, use a component with props-based class strings instead. @apply cannot conditionally apply styles based on runtime state.
