Skip to main content

Overview

Tailwind CSS allows you to define custom utility classes using the @utility directive. This powerful feature enables you to extend the framework with your own reusable utility classes that follow Tailwind’s naming conventions and work with variants.

Static Utilities

Static utilities are simple, single-purpose classes with a fixed value.

Basic Static Utility

This creates a .text-trim utility that applies text trimming properties.

Using Theme Variables

Custom utilities can reference theme variables:
Theme variables are only emitted when the utility is actually used in your markup.

Negative Utilities

You can create negative utilities by prefixing the name with a dash:

Functional Utilities

Functional utilities accept values and must end with -* in their definition.

Basic Functional Utility

The * in the utility name indicates where the value goes, and the * in the property value is replaced with the actual value.

Using Theme Values

Functional utilities can resolve values from your theme:

Arbitrary Values

Functional utilities automatically support arbitrary values:

Multiple Properties

You can use the wildcard value in multiple properties:

Advanced Features

Overriding Core Utilities

You can override or extend built-in utilities:
When overriding core utilities, both your custom version and the core version will be applied. Properties from your custom utility will be merged with core properties.

Overriding Default Values

You can override the default value of functional utilities:

Special Characters

Some special characters are allowed in utility names:
Utility names must be alphanumeric and start with a lowercase letter. The / and % characters are allowed as special cases.

Multiple Definitions

If you define the same utility multiple times, they will be merged:
The result:

Working with Variants

Custom utilities work seamlessly with all Tailwind variants:

Using @apply with Custom Utilities

Custom utilities can be applied using @apply:

Rules and Constraints

Important Rules:
  • @utility must be defined at the top level (not nested)
  • Utility names must be alphanumeric and start with a lowercase letter
  • Functional utilities must end with -*
  • The wildcard (-*) must appear only once, at the end
  • Utility definitions must contain at least one property

Invalid Examples

Best Practices

Recommendations:
  1. Use descriptive, semantic names for your utilities
  2. Keep utilities single-purpose and composable
  3. Reference theme variables when possible for consistency
  4. Document complex utilities with comments
  5. Test utilities with variants before deploying

Source Code Reference

The utility system is implemented in:
  • /packages/tailwindcss/src/utilities.ts:101-155 - Utilities class
  • /packages/tailwindcss/src/utilities.ts:370-376 - staticUtility helper
  • /packages/tailwindcss/src/utilities.ts:393-477 - functionalUtility helper