@apply helps you reuse groups of Tailwind CSS classes by putting them into one custom class. This keeps your code neat and easy to change.
@apply for extracting patterns in Tailwind
.custom-class {
@apply utility-classes;
}Use @apply inside a CSS or Tailwind CSS file.
You list the Tailwind utility classes you want to combine after @apply.
btn class with blue background, white bold text, padding, and rounded corners..btn {
@apply bg-blue-500 text-white font-bold py-2 px-4 rounded;
}card class with shadow, padding, white background, and rounded corners..card {
@apply shadow-lg p-6 bg-white rounded-lg;
}alert style with red background, border, text, padding, and rounded edges..alert {
@apply bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded;
}This example shows a button using a custom btn-primary class. The class uses @apply to combine Tailwind utilities for background color, text color, font weight, padding, rounded corners, and a hover effect.
The button is centered on the page with a light gray background.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>@apply Example</title> <script src="https://cdn.tailwindcss.com"></script> <style> .btn-primary { @apply bg-blue-600 text-white font-semibold py-2 px-4 rounded hover:bg-blue-700; } </style> </head> <body class="flex items-center justify-center min-h-screen bg-gray-100"> <button class="btn-primary" aria-label="Primary action button">Click Me</button> </body> </html>
You must use @apply inside a CSS file processed by Tailwind's build tool.
Not all Tailwind utilities can be used with @apply (for example, arbitrary value utilities like w-[100px] or certain complex utilities).
Using @apply helps keep your HTML cleaner and your styles consistent.
@apply lets you combine Tailwind classes into one custom class.
It helps reuse styles and keep your code tidy.
You write @apply inside CSS to extract patterns from utility classes.