Reusing Styles With @apply

Bundle utilities into a custom class using @apply.

Syntax.btn { @apply px-4 py-2 rounded bg-cyan-500 text-white; }

Sometimes you want a reusable class like .btn. The @apply directive inlines utility styles into your own CSS class.

.btn {
  @apply px-4 py-2 rounded-lg bg-cyan-500 text-white;
}

The example uses a plain <style> block to mimic the result so you can see the button.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A developer extracts a repeated button pattern into a .btn-primary class using @apply to avoid copying the same ten utilities across dozens of templates.
  • A prose content area bundles heading and paragraph typography utilities into a .prose class so CMS content is styled automatically.
  • A team creates shared .form-input and .form-label component classes with @apply to enforce consistent form styling across all projects.

More examples

Button component via @apply

@apply bundles all the button's utility classes into .btn-primary, so HTML templates only need class="btn-primary" instead of the full list.

Example · css
/* src/styles.css */
@layer components {
  .btn-primary {
    @apply bg-indigo-600 text-white font-medium px-5 py-2 rounded
           hover:bg-indigo-700 focus:outline-none focus:ring-2
           focus:ring-indigo-500 focus:ring-offset-2 transition;
  }
}

Using the extracted class

Once .btn-primary is defined with @apply, every button gets the full utility set from a single short class name.

Example · html
<button class="btn-primary">Save Changes</button>
<button class="btn-primary">Create Account</button>

Form input component

A .form-input component class ensures every text input in the project shares the same border, padding, color, and focus-state styles.

Example · css
@layer components {
  .form-input {
    @apply w-full border border-gray-300 rounded px-3 py-2
           text-sm text-gray-900
           focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500
           focus:outline-none;
  }
}

Discussion

  • Be the first to comment on this lesson.