@apply, @layer and @variants in Tailwind CSS
Tailwind provides powerful directives like @apply
, @layer
, and @variants
to help you manage custom styles while staying in the utility-first mindset.
1. Using @apply
The @apply
directive lets you extract commonly-used utility classes into custom CSS classes.
/* styles.css */ .btn { @apply px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700; }
Now you can use class="btn"
in your HTML to apply all these utilities.
2. Using @layer
Tailwind has three layers: base
, components
, and utilities
. Use @layer
to add styles to the correct part of the cascade.
@tailwind base; @tailwind components; @tailwind utilities; @layer components { .card { @apply p-6 bg-white rounded shadow; } }
3. Using @variants
(optional)
While @variants
is no longer required with JIT, it used to define variants like :hover
or :focus
. With JIT, just use them inline or inside @layer.
@layer components { .btn-danger { @apply bg-red-500 text-white hover:bg-red-600; } }
4. Best Practices
- Use
@apply
for repeating utility patterns. - Organize custom styles in
@layer components
. - Let Tailwind handle most variants automatically in JIT mode.
Conclusion
These directives enhance Tailwindβs flexibility, allowing you to maintain clean, reusable styles while still leveraging utility-first benefits.