Overview
Tailwind CSS provides two ways to create custom variants:@custom-variant for defining new variants and @variant for applying existing variants within custom utilities or other contexts.
@custom-variant Directive
The@custom-variant directive allows you to create entirely new variants that can be used throughout your project.
Body-less Syntax
The simplest way to define a variant is using the body-less syntax with a selector list.Selector Variants
hocus: variant that applies styles when the element is hovered or focused.
The
& symbol represents the element the utility is applied to. Multiple selectors are comma-separated.At-Rule Variants
Mixed Selectors and At-Rules
You can combine both selector and at-rule conditions:Body with @slot Syntax
For more complex variants, use the body syntax with@slot to mark where utilities should be inserted.
Basic @slot Usage
Nested Structures
Using @variant Inside Definitions
You can compose variants by using@variant within @custom-variant bodies:
@variant Directive
The@variant directive applies an existing variant within custom utility or variant definitions.
In Custom Utilities
Apply variants directly in utility definitions:Composing Multiple Variants
Nest@variant directives to combine conditions:
Compound Variants
Tailwind includes compound variants that modify how other variants work.group Variant
Thegroup compound variant is implemented in the source code:
peer Variant
Similar togroup, but for sibling elements:
not Variant
Thenot variant negates another variant:
in Variant
Applies styles when the element is inside another element:has Variant
Applies styles when the element contains a matching child:Variant Ordering
Variants have a specific order that determines their precedence:Advanced Variant Features
Functional Variants
Functional variants accept values:Custom Dark Mode Variant
Override the default dark mode implementation:Breakpoint-like Variants
Rules and Constraints
Invalid Examples
Best Practices
Source Code Reference
The variant system is implemented in:/packages/tailwindcss/src/variants.ts:39-317- Variants class/packages/tailwindcss/src/variants.ts:348-1163- createVariants function/packages/tailwindcss/src/variants.ts:86-110- fromAst method for @custom-variant/packages/tailwindcss/src/variants.ts:1210-1235- substituteAtVariant function