@apply Usage
- Use the @apply directive to create reusable Tailwind CSS styles.
Tailwind is utility-first, but professional projects also need:
Clean HTML
Reusable patterns
Maintainable code
The @apply directive helps achieve this -
when used correctly.This lesson focuses on:
When to use @apply
When NOT to use it
How professionals use it without hurting performance
What is @apply? (Quick Recall)
@apply allows you to:
Combine multiple Tailwind utility classes into a single custom CSS class.
In simple words:
It lets you reuse utility patterns.
Why @apply Exists
Tailwind encourages utilities, but:
Long class lists get repeated
Buttons, inputs, cards need consistency
Large teams need shared styles
@apply solves repetition, not everything.
Where @apply Should Be Used
@apply is best used for:
Buttons
Form inputs
Badges
Cards
Common layout patterns
Correct Place to Use @apply
Always use @apply inside Tailwind layers:
@layer components {
/* @apply here */
}
This ensures:
Proper CSS order
No specificity issues
Predictable behavior
Reusable Primary Button with @apply
This creates a reusable button class using Tailwind’s @apply for consistent styling and cleaner HTML.
@layer components {
.btn-primary {
@apply bg-blue-500 text-white
px-4 py-2 rounded-md
hover:bg-blue-600
focus:ring-2 focus:ring-blue-400
transition;
}
}
/* Usage */
<button class="btn-primary">
Submit
</button>
Why This is Good
Clean HTML
Centralized styling
Easy updates
Consistent UI
Base Input Class with @apply
This creates a reusable base input class for consistent styling across all form fields.
@layer components {
.input-base {
@apply w-full border border-gray-300
rounded-md px-3 py-2 text-sm
focus:outline-none
focus:ring-2 focus:ring-blue-400
focus:border-blue-500;
}
}
/* Usage */
<input class="input-base" />
This is real-world, professional form styling.
What NOT to Use @apply For
Do NOT use @apply for:
One-time styles
Small layout tweaks
Responsive logic overload
Dynamic state combinations
Everything in the project
Example of bad usage:
.card {
@apply flex flex-col md:flex-row lg:gap-6;
}
This removes Tailwind’s clarity and flexibility.
@apply vs Utility Classes
Use Case Recommendation Repeated UI patterns @apply Buttons / Inputs @apply One-off layout Utilities Responsive layout logic Utilities Dynamic state styling Utilities
Rule:
Use @apply for reusable components, not layout logic.
Performance Considerations with @apply
Good @apply usage:
Does NOT hurt performance
Improves maintainability
Bad @apply usage:
Increases CSS size
Creates bloated components
Reduces clarity
Overusing @apply defeats Tailwind’s purpose.
Common Beginner Mistakes
Putting everything into @apply
Creating too many custom classes
Ignoring Tailwind layers
Mixing layout + component styles
Using @apply instead of learning utilities
If CSS starts looking like Bootstrap → misuse happened.