Introducing a new way to review your PRs.

Read the announcement

tailwindlabs / tailwindcss

A utility-first CSS framework for rapid UI development.

View on GitHub

19 documents · Updated Nov 20, 2026

docs / utility-and-variant-compilation

Utility and variant compilation

Utility and variant compilation turns class candidates into CSS rules. It gives each class a clear meaning, finds the value for its utility, applies its conditions, canonicalizes equivalent forms, and orders the result so the final stylesheet has stable cascade behavior. This page is a child of Compiler and CSS generation and relates to CSS directives and parsing, Theme and design tokens, and Content discovery and scanning.

Candidate model

The candidate model is the structured meaning of a class name after parsing. It keeps the base utility or direct CSS property together with its variants, value, modifier, and important state. The parser can yield more than one utility interpretation when a name can be split at different dashes. Later compilation chooses the interpretation that produces a valid rule.

References: packages/…/candidate.ts• L104-219 packages/…/candidate.ts• L323-631

Candidate forms

Candidates use one of three forms:

FormPurposeExample shape
StaticSelects a utility with no value segment.underline
FunctionalSelects a utility and supplies a named value, fraction, or arbitrary value.bg-red-500, w-1/2, bg-[#0088cc]
Arbitrary propertySupplies a CSS property and value directly.[color:red]

Functional and arbitrary candidates can have one modifier. Any second top-level slash segment makes the candidate invalid, even when that segment is empty. Arbitrary values and selectors must have balanced delimiters and must not close a declaration or block at the top level. A CSS comment start is also rejected unless it is in a safe string or declaration URL form. A trailing ! marks the candidate as important. The older leading ! form is normalized to the same meaning. A configured prefix is required at the start of the class and is removed from the parsed variant list. The parser limits stacked variants to protect compilation from pathological input.

References: packages/…/candidate.ts• L317-446 packages/…/candidate.ts• L461-631 packages/…/candidate.ts• L681-906 packages/…/candidate.test.ts• L1834-2080

Variant forms

Variants describe the condition or selector around a utility. The parser supports static variants such as hover, functional variants such as data-[disabled] or @lg, arbitrary selector variants such as [&_p], and compound variants such as group-hover or has-[&_p]. A compound variant contains another parsed variant, so a parent condition can change the child rule without treating the full class as opaque text.

References: packages/…/candidate.ts• L94-163 packages/…/candidate.ts• L696-906 packages/…/candidate.test.ts• L93-369

Candidate normalization

Candidate normalization gives equivalent class spellings one stable meaning. It decodes underscores into spaces where CSS permits them and keeps underscores in CSS variable names and URLs. When it prints arbitrary values, it removes redundant whitespace while preserving spaces that change selector meaning. It can also wrap a custom CSS function when an adjacent operator would make the printed value unclear. The important marker is printed in one position. The normalized form is useful when the same class is parsed by different parts of the compiler.

References: packages/…/candidate.ts• L973-1309 packages/…/candidate.ts• L1309-1314 packages/…/candidate.test.ts• L941-1183 packages/…/candidate.test.ts• L2082-2186

Candidate canonicalization

Candidate canonicalization maps equivalent utility and variant spellings to a common class form before later work compares or emits them. It also permits safe utility collapse when several classes with the same variants and important state express the same property values. The result removes duplicate work while preserving theme-variable meaning and CSS order.

Canonicalization works in two related stages:

  • It canonicalizes each utility and variant, including safe escape forms and compatible value notation.
  • When enabled, it replaces groups of utilities only when their property and value signatures match and the replacement uses compatible theme variables.

References: packages/…/canonicalize-candidates.ts• L206-225 packages/…/canonicalize-candidates.ts• L227-271 packages/…/canonicalize-candidates.ts• L610-680 packages/…/canonicalize-candidates.ts• L1038-1111

Utility lookup and value resolution

The design system connects candidate parsing with utility matchers, variant definitions, and theme data. Compilation first turns a candidate into declarations. It then uses those declarations as the base rule for variant application.

References: packages/…/design-system.ts• L35-60 packages/…/design-system.ts• L70-105 packages/…/compile.ts• L129-181

Utility matching

The utility registry groups matchers by utility root. A matcher can handle a static utility or a functional value. Normal matchers run before fallback matchers. A matcher can decline a candidate or return no declarations when the value is not valid. A supplied modifier must be consumed by the matcher; otherwise a valid base value does not silently produce the same rule as the unmodified class. Fractions are the main exception because the slash can form part of the value itself. If no matcher produces declarations, compilation discards the candidate.

Static entries represent supported CSS declarations rather than every name that could be written as a class. A value is therefore compiled only when the utility set defines it as valid for that CSS property. For example, valid justify-content choices are registered while the invalid justify-baseline utility is not.

References: packages/…/utilities.ts• L71-165 packages/…/utilities.ts• L403-497 packages/…/utilities.ts• L2123-2140 packages/…/compile.ts• L277-347

Theme value resolution

Named values resolve through theme namespaces such as color, spacing, and font. The theme finds the matching token and returns either a CSS variable reference or an inline token value when the utility needs it. A missing token does not create a rule. Special color names such as current, inherit, and transparent do not need a theme entry.

References: packages/…/theme.ts• L168-190 packages/…/theme.ts• L219-243 packages/…/utilities.ts• L218-290

Value paths

Utilities use several value paths. The selected path controls whether the class can resolve and whether its modifier has meaning:

  • A named value looks up a theme token.
  • A fraction can become a percentage when the utility supports fractions.
  • A bare value can be accepted when the utility defines a safe bare-value rule.
  • An arbitrary value is passed through with an optional type hint.
  • A modifier can resolve through the opacity theme or through a valid direct opacity value.

The slash in a class can be ambiguous. The parser keeps a possible fraction such as 1/2 with the named value while also recording a modifier when the syntax supports one. The utility matcher decides which meaning applies. Square brackets accept arbitrary CSS values. Parentheses provide a shorthand for CSS variables such as bg-(--my-color).

References: packages/…/candidate.ts• L388-679 packages/…/utilities.ts• L403-497 packages/…/utilities.ts• L508-541

Functional utility value expressions

Custom functional utilities define a value contract for a class family. Their declarations can accept a theme token, a constrained bare value, an arbitrary value, or a literal. They can also define a default for a missing value and a separate contract for a slash modifier.

The candidate produces a rule only when at least one value expression resolves. If a supplied modifier does not resolve, or if a fraction and a modifier are used in incompatible ways, the utility is discarded. This lets one utility family support several value forms without emitting partial or misleading CSS.

References: packages/…/utilities.ts• L6305-6424 packages/…/utilities.ts• L6474-6626 packages/…/utilities.test.ts• L30317-30595 packages/…/utilities.test.ts• L30666-31217

Variant application

Variant application wraps or changes the base rule so the utility applies only under its condition. The compiler applies the parsed variants to the utility rule in their candidate order. If a variant cannot operate on the rule shape, the complete candidate produces no rule.

References: packages/…/compile.ts• L129-181 packages/…/compile.ts• L183-275

Selector and at-rule variants

Variants can add a selector or place the declarations inside an at-rule. State variants add selectors such as :hover or an ARIA attribute. Responsive variants add media queries whose values come from breakpoint theme tokens. Container variants use the same model with container query rules. Group and peer variants keep the utility target inside the generated selector so the browser can limit style recalculation to elements that use the rule. This preserves their matching behavior while reducing work when a group or peer changes state.

References: packages/…/variants.ts• L365-382 packages/…/variants.ts• L578-681 packages/…/variants.ts• L747-890 packages/…/variants.ts• L995-1203

Arbitrary and compound variants

An arbitrary variant supplies a selector or at-rule directly. A selector that starts with a relative combinator is valid only inside a compound variant because it cannot form a complete top-level selector. Other arbitrary selectors gain an implicit subject when needed. A compound variant applies its child to an isolated rule first. The parent then changes that rule and inserts it into the final utility rule.

Compound variants also carry compatibility rules. The parent declares which kind of child rule it can contain. Parsing rejects an incompatible pair before compilation. Some compound variants forward their modifier to the nested variant so named groups can continue through several compound levels. Compound nesting has a finite safety limit so malformed or generated input cannot exhaust the call stack.

References: packages/…/candidate.ts• L696-906 packages/…/variants.ts• L36-40 packages/…/variants.ts• L171-203 packages/…/variants.ts• L330-356 packages/…/compile.ts• L217-269

The following flow shows how a class becomes a final rule or is discarded when one stage cannot produce valid CSS.

flowchart LR
  A[Raw class] --> B[Parse candidate]
  B -->|valid interpretation| C[Find utility]
  C --> D[Resolve value]
  D -->|declarations| E[Create base rule]
  E --> F[Apply variants]
  F -->|applicable| G[Record CSS rule and sort data]
  B -->|invalid| X[Discard class]
  C -->|no matcher| X
  D -->|no value| X
  F -->|incompatible| X

Ordering rules

Ordering determines which generated rule wins when selectors have equal relevance. The compiler records variant order and property order for each rule, then sorts the AST by those keys instead of using the order of class names in source input.

References: packages/…/compile.ts• L19-24 packages/…/compile.ts• L48-121

Variant order

Variants are registered in ordered groups. Variants in one group share an order number. A comparison rule can order values inside the group, which is important for breakpoint and container values. Named values sort before arbitrary values. Compound variants compare their nested variant before their own modifier.

References: packages/…/variants.ts• L62-73 packages/…/variants.ts• L152-157 packages/…/variants.ts• L214-280

The design system turns the sorted variant list into order groups. A candidate records the groups used by its variants as a bit set. The compiler compares this set first. Variant conditions therefore control the main cascade position before declaration properties do.

References: packages/…/design-system.ts• L190-212 packages/…/compile.ts• L64-73 packages/…/compile.ts• L97-100

When the compiler receives one candidate, it skips building the shared variant-order map because no other candidate needs comparison. This keeps single-candidate compilation correct while avoiding the cost of sorting all registered variants. Multi-candidate compilation still builds the map so generated rules keep their cross-candidate cascade order.

References: packages/…/compile.ts• L48-52 packages/…/compile.ts• L64-73

Property order

After variant order, rules are compared by the global property order of their declarations. Rules with the same first property position are then ordered by declaration count, with rules that contain more properties first. The raw candidate is the final tie breaker. A --tw-sort declaration can set a rule's property position when it names a known global property.

References: packages/…/compile.ts• L89-121 packages/…/compile.ts• L366-407

Important declarations

The candidate's important marker makes its declarations important. A design-system-wide important setting can do the same when the compile call respects that setting. At-root nodes such as keyframe or property definitions are left unchanged.

References: packages/…/compile.ts• L42-46 packages/…/compile.ts• L137-157 packages/…/compile.ts• L350-364

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep candidate parsing, utility root registration, and candidate printing aligned. A new value shape must parse into the form its matcher expects and print back to the same class meaning.
  • Keep prefix handling aligned with candidate printing. A prefixed class must parse only when the prefix is first and must print with that prefix restored.
  • Keep arbitrary value and modifier validation aligned across utilities and variants. Empty values, unsafe top-level delimiters, CSS comment starts, and invalid variable shorthands must fail in the same way.
  • Keep delimiter validation aligned with arbitrary value decoding. Validate raw input before decoding so unbalanced brackets or parentheses do not reach utility or variant resolution.
  • Keep the slash ambiguity aligned with utility matching. A change to modifier parsing can change whether a fraction reaches a matcher as a fraction or as a modifier. Reject every extra top-level slash segment for both utilities and variants.
  • Keep custom functional utility value and modifier branches aligned with candidate forms. A branch that resolves no value, or accepts an unsupported modifier, must not emit a partial rule.
  • Keep canonicalization changes aligned with candidate printing and theme-variable use. A shorter or newer spelling is safe only when it preserves the same declarations and theme meaning.
  • Keep variant registration order and comparison rules aligned with the intended cascade. Breakpoint and container values must use the same theme lookup rules for application and sorting.
  • Keep compound compatibility metadata aligned with the rule shape a variant generates. Modifier forwarding must also preserve the intended nested variant meaning.
  • Keep group and peer selector shape aligned with the target represented by &. This preserves @apply, nested variants, and the intended browser style invalidation scope.
  • Keep property-order changes aligned with --tw-sort handling. A custom sort marker works only when its value exists in the global property order.
  • Preserve the candidate depth limits and root-length bounds. They protect parsing and compilation from generated classes with excessive variant or dash chains without changing normal candidates.
  • Preserve the single-candidate optimization in compileCandidates. Variant order is needed for cross-candidate sorting, not for a single candidate, so restoring unconditional order-map creation can make canonicalization slow without changing CSS output.

Important failure modes

TriggerConsequenceGuard
A class does not include the configured prefix in the required position.Parsing yields no candidate, so no CSS rule is generated.Use the configured prefix before all variants and the utility.
A utility or variant contains more than one top-level slash segment.The candidate is rejected, including when the extra segment is empty.Use at most one modifier and keep fractions in the utility value syntax that supports them.
A named utility value has no matching theme key.The candidate produces no CSS and is invalid for compilation.Use a value in the utility's theme namespace or use a supported arbitrary value.
A class names a CSS value that has no registered utility matcher, such as justify-baseline.No declarations are produced and the class has no effect.Use a utility backed by a valid CSS declaration.
A slash is interpreted as a modifier but the utility expects a fraction.The utility receives the wrong value path and can produce no rule.Keep fraction support and modifier handling aligned in the utility matcher.
An arbitrary value or modifier is empty or contains a top-level ; or }.The candidate is rejected before it can reach a utility or variant matcher.Use a non-empty CSS value without declaration or block terminators at the top level.
An arbitrary value or selector has unbalanced brackets or parentheses.The candidate is rejected before value or variant resolution.Keep arbitrary syntax balanced before it is encoded in a class.
An arbitrary value contains an unsafe CSS comment start.The candidate is rejected instead of allowing the comment to hide later CSS rules.Put literal comment text in a safe string or use a valid declaration URL form.
A resolved utility value has an unsupported modifier.The class is discarded instead of generating the same CSS as the unmodified class.Use a modifier supported by that utility or omit it.
A custom functional utility has no resolving value branch.The candidate produces no CSS, even if its family name is registered.Provide a matching theme, bare, arbitrary, literal, or default value branch.
Canonicalization replaces utilities with different theme-variable meaning.The output can match the default CSS while changing behavior when a theme variable is overridden.Require matching theme-variable signatures before collapsing utilities.
A relative arbitrary selector is used as a top-level variant.The candidate is discarded because the selector cannot form a complete variant rule.Use the relative selector inside a compatible compound variant.
A compound variant receives a child with an unsupported rule kind.The candidate is rejected before or during variant application.Check the parent and child compound capability metadata.
A candidate exceeds the stacked or compound variant depth limit.The candidate is discarded before it can exhaust parser or CSS tree call depth.Keep generated variant chains within the supported limits.
A variant cannot apply to the generated AST.The whole candidate produces no rule even when its base utility is valid.Use variants that match the rule shape produced by the utility.
Variant order is calculated for one candidate during repeated canonicalization.Compilation can spend time sorting variants that do not affect the result.Build the variant-order map only when more than one candidate must be compared.

Key files

FileWhy to read it
packages/…/candidate.tsCandidate and variant forms, value syntax, validation, safety limits, and canonical class printing.
packages/…/canonicalize-candidates.tsEquivalent candidate forms, safe utility collapse, and preservation of theme and variant meaning.
packages/…/compile.tsMain lifecycle from utility compilation through variant application and final rule ordering.
packages/…/utilities.tsUtility registry and value paths for theme, fraction, bare, arbitrary, color, modifier, and custom functional values.
packages/…/variants.tsVariant behavior, compound compatibility, selector targets, and comparison rules.
packages/…/theme.tsTheme key lookup and the choice between CSS variable references and inline token values.
packages/…/design-system.tsThe boundary that connects parsing, registries, theme data, caching, and compilation.
packages/…/candidate.test.tsThe contract for accepted candidate shapes, safe arbitrary syntax, normalization, prefixes, modifiers, depth limits, and nested variants.
packages/…/utilities.test.tsThe contract for theme, bare, arbitrary, fraction, default, and modifier resolution in utility families.
packages/…/sort.tsThe class-to-order mapping used by consumers that need the compiler's cascade order.