@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:@apply:
Functional Utilities
Create utilities that accept a value using the-* suffix:
--value variable is automatically replaced with the utility value:
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 usingvar():
Nested Rules
Utilities can contain nested rules using the& selector:
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
Parsing and Processing
When you define a utility with@utility, the parser:
- Validates the utility name according to naming rules
- Checks for the
-*suffix to determine if it’s functional - Extracts the CSS declarations from the body
- Registers the utility in the design system
- Makes it available to
@applyand class names - Removes the
@utilityrule from the final CSS
Output
The@utility directive itself does not appear in the final CSS. Only the generated utility classes are output when used: