0
0
Tailwindmarkup~5 mins

@apply for extracting patterns in Tailwind

Choose your learning style9 modes available
Introduction

@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.

You want to use the same set of styles on many elements without repeating all classes.
You want to create a custom button style that you can reuse across your site.
You want to keep your HTML cleaner by moving complex class lists into CSS.
You want to update a style in one place and have it change everywhere.
You want to organize your styles better when your project grows.
Syntax
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.

Examples
This creates a btn class with blue background, white bold text, padding, and rounded corners.
Tailwind
.btn {
  @apply bg-blue-500 text-white font-bold py-2 px-4 rounded;
}
This makes a card class with shadow, padding, white background, and rounded corners.
Tailwind
.card {
  @apply shadow-lg p-6 bg-white rounded-lg;
}
This defines an alert style with red background, border, text, padding, and rounded edges.
Tailwind
.alert {
  @apply bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded;
}
Sample Program

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.

Tailwind
<!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>
OutputSuccess
Important Notes

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.

Summary

@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.