Skip to main content
The @utility directive allows you to define custom utility classes that integrate seamlessly with Tailwind CSS. These utilities can be applied using regular class names or with @apply.

Syntax

Basic Usage

Static Utilities

Create a simple static utility that always generates the same CSS:
Use it like any built-in utility:
Or with @apply:

Functional Utilities

Create utilities that accept a value using the -* suffix:
The --value variable is automatically replaced with the utility value:
You can also use theme values:

Utility Naming Rules

string
Must be alphanumeric, start with a lowercase letter, and can contain hyphens:
string
Must end with -* and follow the same naming rules:

Using CSS Variables

The —value Variable

For functional utilities, --value represents the user-provided value:

Referencing Theme Variables

You can reference theme variables using var():

Nested Rules

Utilities can contain nested rules using the & selector:
Generated HTML class:
Generated CSS:

Pseudo-elements

Create utilities with pseudo-elements:

Using @apply in Utilities

You can use @apply within custom utilities:
Utilities defined with @utility are available to @apply even before they are defined in the source order.

Recursive Application

Utilities can recursively apply other custom utilities:

At-Rules and Media Queries

Include media queries and other at-rules:

Restrictions

The @utility directive must be used at the top level and cannot be nested inside other rules.
Custom utilities must include at least one CSS property. Empty utilities are not allowed.

Parsing and Processing

When you define a utility with @utility, the parser:
  1. Validates the utility name according to naming rules
  2. Checks for the -* suffix to determine if it’s functional
  3. Extracts the CSS declarations from the body
  4. Registers the utility in the design system
  5. Makes it available to @apply and class names
  6. Removes the @utility rule from the final CSS
From the source code (index.ts:222-254):

Output

The @utility directive itself does not appear in the final CSS. Only the generated utility classes are output when used: