3 min read
•Question 25 of 38mediumWhat is @apply directive in Tailwind?
Extracting component classes.
What You'll Learn
- @apply syntax
- When to use it
- Best practices
Basic Usage
styles.cssCSS
/* In your CSS file */
.btn {
@apply px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600;
}
.card {
@apply bg-white rounded-lg shadow-md p-6;
}With Tailwind CSS v3+
styles.cssCSS
@layer components {
.btn-primary {
@apply px-4 py-2 bg-blue-500 text-white rounded;
@apply hover:bg-blue-600 focus:ring-2 focus:ring-blue-300;
}
}When to Use
Good use cases:
- Repeated patterns across many files
- Third-party integration needs class names
- CMS content styling
Avoid when:
- Used once or twice (just use utilities)
- Can use React/Vue components instead
Prefer Components
code.txtJSX
// Better approach in React
function Button({ children }) {
return (
<button className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
{children}
</button>
)
}