If you're using Tailwind CSS with Next.js or other modern frameworks, you've likely come across directives like @layer base
, @layer components
, and @layer utilities
. But what's the difference between them, and how should they be used?
This article explains each of them with practical examples to help you better structure your styles using Tailwind.
@layer base
For global resets and initial styles
This is the first layer loaded. Ideal for:
- Resetting styles
- Setting global fonts
- Basic element styles like
body
,h1
,button
, etc.
@layer base {
h1 {
@apply text-3xl font-bold text-gray-900;
}
body {
@apply bg-background text-foreground font-sans;
}
}
@layer components
For reusable components (buttons, cards, badges, etc.)
Loaded after base
and before utilities
. Perfect for blocks of combined utility classes:
@layer components {
.btn {
@apply px-4 py-2 bg-purple-600 text-white rounded-md;
}
.card {
@apply shadow-md rounded-lg p-4 bg-white;
}
}
@layer utilities
For custom utilities
The last layer to load. Best used for specific, override-style utilities:
@layer utilities {
.text-shadow {
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}
.scrollbar-none {
scrollbar-width: none;
-ms-overflow-style: none;
}
}
Load order summary
@layer base <- Global styles
@layer components <- Reusable components
@layer utilities <- Specific utilities (highest priority)
Practical tip
Use each like this:
-
base
: for tag resets and global defaults -
components
: for.btn
,.card
,.input
, etc. -
utilities
: for.text-shadow
,.scroll-smooth
, etc.
Practical example with menu UI
@layer components {
.promo-price {
@apply text-purple-600 font-bold;
}
.add-button {
@apply px-4 py-1 bg-gray-200 rounded text-sm font-medium;
}
}
Have you been using them correctly? Share your thoughts! 🚀
Top comments (8)
Nice summary. Thanks for sharing!
Thankss!!
Thanks for posting!
wow. thanks, man.
Awesome, I learned new one!
wow. thanks, man.
Super clear breakdown....this definitely clears up the mental model for using @layer properly....more of us needed to hear this honestly...
Thank you for you feedback.