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 / compiler-and-css-generation

Compiler and CSS generation

The Tailwind CSS compiler turns authored CSS and the class candidates used by an application into final CSS. It keeps authored rules, connects candidates to theme data and utility rules, and emits styles only for valid candidates. The public tailwindcss package exposes this work through CSS entrypoints and compiler APIs.

Compiler boundary

The compiler accepts authored CSS and a set of class candidates. It returns transformed CSS plus feature and source information for build tools. A separate design-system view lets editors and other tools inspect what a candidate can produce without building a full application stylesheet.

The public core package provides three related boundaries:

  • compile accepts CSS text and returns a build function that produces CSS text.
  • compileAst accepts a CSS syntax tree and returns a build function that produces a transformed tree.
  • __unstable__loadDesignSystem prepares theme data, utilities, and variants for tooling use.

The build function is incremental. It remembers valid candidates that it has seen and can reuse the prior result when the candidate set does not change the output. It also reports source roots and compiler features so a build tool can coordinate content discovery and diagnostics. Content discovery and scanning describes how candidate input reaches this boundary.

References: packages/…/index.ts• L715-857 packages/…/index.ts• L861-912 packages/…/design-system.ts• L35-68

CSS transformation flow

The compiler combines the authored stylesheet with generated utility CSS at the @tailwind utilities entrypoint. It prepares the CSS and design system, reads class candidates, creates rules, resolves nesting and special CSS behavior, and prints the final tree.

This diagram shows how authored input and discovered classes become one stylesheet.

flowchart LR
  A[Authored CSS] --> B[CSS syntax tree]
  B --> C[Theme and directive setup]
  D[Class candidates] --> E[Candidate parsing]
  C --> E
  E --> F[Utility and variant rules]
  F --> G[Sorted CSS tree]
  C --> G
  G --> H[Optimized CSS]

Authored rules remain in the result. Generated utility rules replace the utilities entrypoint. The compiler can keep generated utility nodes across builds and print them again without rebuilding unchanged parts. If the input has no feature that needs compiler work, the original input can pass through unchanged.

References: packages/…/index.ts• L143-221 packages/…/index.ts• L604-711 packages/…/index.ts• L754-855 packages/…/ast.ts• L230-705

Candidate-to-style transformation

A class candidate is a class name that Tailwind tries to turn into a CSS rule. The compiler separates variants from the utility, checks the value, resolves the utility against the design system, and applies the variants to the resulting rule.

The candidate model supports:

  • Static utilities such as underline.
  • Functional utilities with named values such as bg-red-500.
  • Arbitrary properties and values such as [color:red] and bg-[#0088cc].
  • Static, functional, arbitrary, and compound variants.
  • Modifiers and important forms.

Invalid candidates produce no CSS. Arbitrary values must have balanced delimiters and cannot contain a top-level semicolon, an unsafe comment start, or an invalid string boundary. This lets candidate discovery inspect broad input without emitting unsafe or meaningless rules. A limit on stacked variants and flattened selector size also prevents one candidate from creating unbounded work.

The compiler applies each valid candidate in this order:

  1. Resolve the base utility to declarations. Direct arbitrary properties and registered utility handlers use the same rule-building path.
  2. Mark declarations as important when the candidate or compilation context requires it.
  3. Apply variants to selectors or at-rules.
  4. Discard the candidate if a value or variant cannot produce a valid rule.
  5. Sort the result by variant precedence and declaration properties.

The detailed rules for directives and parsing are in CSS directives and parsing. Utility and variant behavior is in Utility and variant compilation.

References: packages/…/candidate.ts• L317-631 packages/…/candidate.ts• L696-906 packages/…/compile.ts• L22-137 packages/…/compile.ts• L140-307 packages/…/is-valid-arbitrary.ts• L36-180

Design-system assembly

The design system is the shared context that connects theme values with utility and variant generation. The compiler builds it after reading authored CSS, then adds custom utilities and variants before it processes candidates.

The same context serves stylesheet generation and editor tooling. It caches parsed candidates and compiled rules while the context remains valid. It also tracks theme variables used by generated declarations so unused theme data can be removed from the output. The broader token model is described in Theme and design tokens.

Variant ordering is recalculated when the known variant set grows. This keeps candidate inspection and stylesheet generation aligned as CSS adds new variants.

References: packages/…/design-system.ts• L70-114 packages/…/design-system.ts• L116-223 packages/…/index.ts• L604-653

Candidate normalization

Candidate normalization turns equivalent class spellings into stable forms before tools compare or rewrite them. It can migrate older value forms to current theme-variable forms, normalize arbitrary values and variants, and optionally replace several utilities with one equivalent utility.

Normalization is separate from CSS rule generation. Its contract is semantic equivalence: a replacement must keep the same declarations and must not change the theme variables that those declarations use. Variant signatures now include rules carried through @scope, so a scoped variant is not treated as equivalent to a variant that generates no scope. This supports editor output and class rewriting without silently changing a design token, selector scope, or the cascade.

Normalization also follows CSS identifier escape rules when candidates contain escaped punctuation or unusual code points. It can simplify equivalent escapes and arbitrary expressions, but it keeps escapes when removing them would change CSS meaning. At-rule parameters are normalized only where whitespace does not change selector meaning. Malformed input remains a stable candidate instead of crashing a build or becoming an invalid variable name.

References: packages/…/canonicalize-candidates.ts• L206-225 packages/…/canonicalize-candidates.ts• L610-679 packages/…/canonicalize-candidates.ts• L1038-1111 packages/…/canonicalize-candidates.ts• L3373-3599 packages/…/index.test.ts• L1648-1665

CSS input parsing

The CSS parser converts authored CSS into the tree that drives directive expansion and later CSS generation. It recognizes rules, declarations, at-rules, nesting, strings, comments, and custom properties while keeping the source text needed for diagnostics.

The parser removes ordinary comments but collects license comments at the start of the tree. It accepts declarations and at-rules without a final semicolon when the input ends. It treats custom property values as broad CSS data, so semicolons and braces inside balanced functions or blocks do not end the value too early.

The parser reports invalid structure as CssSyntaxError. Unbalanced blocks, missing declaration values, and unterminated strings stop the transformation. When the caller provides a source name, the error includes a file, line, and column. This gives later compiler stages a stable tree and gives build tools useful input locations.

The parser keeps escaped characters and quoted strings from changing the meaning of delimiters. It also normalizes line endings during scanning and preserves meaningful whitespace in selectors and values. The parser behavior is covered for Unix and Windows line endings, nested CSS, custom properties, at-rules, comments, and source-located errors.

References: packages/…/css-parser.ts• L40-70 packages/…/css-parser.ts• L115-167 packages/…/css-parser.ts• L203-345 packages/…/css-parser.ts• L347-647 packages/…/css-parser.ts• L650-825 packages/…/css-parser.test.ts• L6-16 packages/…/css-parser.test.ts• L1382-1524

Selector and nesting transformation

Selectors are represented as structured values while the compiler resolves nesting and variants. This lets the compiler replace & safely, preserve selector-list meaning, and distinguish selectors that can never match from selectors that can still contain live nested rules.

The final AST also normalizes nested rules and hoists supported at-rules. Relative selectors inside @scope receive an explicit scope root so their meaning survives hoisting and later CSS processing. The result is a CSS tree that can be printed without losing selector or scope behavior.

References: packages/…/selector-parser.ts• L43-50 packages/…/selector-parser.ts• L185-218 packages/…/selector-parser.ts• L241-637 packages/…/compile.ts• L199-291 packages/…/ast.ts• L707-1276 packages/…/ast.ts• L1452-1718

CSS entrypoints

The public package provides CSS entrypoints that let an authored stylesheet choose the Tailwind layers it needs. The full entrypoint composes theme data, the base reset, and utilities in named cascade layers.

Entry pointSystem role
tailwindcss or tailwindcss/index.cssFull theme, base, and utility CSS
tailwindcss/theme.cssDefault theme data and design tokens
tailwindcss/preflight.cssBase browser reset and element rules
tailwindcss/utilities.cssUtility generation through @tailwind utilities

The export map makes these CSS paths public. The package root also exposes the compiler API for JavaScript consumers. The CSS entrypoints are therefore the stylesheet contract, while the compiler functions are the programmatic contract.

References: packages/…/index.css• L1-5 packages/…/package.json• L19-66 packages/…/package.json• L110-127 packages/…/theme.css• L1-10 packages/…/preflight.css• L1-16 packages/…/utilities.css• L1

Generated stylesheet structure

The generated stylesheet keeps the main authored layers and places theme variables and utility rules where the input requires them. Used theme variables remain available to generated rules, while unused variables and unused theme keyframes can be removed.

Generated rules use a stable order. Variant precedence comes first. Property order then resolves ties. Rule size and candidate name provide stable fallbacks. This order is part of the output contract because it controls which utility wins when declarations overlap.

The printer converts the final CSS tree back to CSS text. Cached utility nodes can reuse their printed CSS across builds, but source-map builds print with current source positions. The AST pass also preserves source information while it handles scope, nesting, fallbacks, and unused theme data.

References: packages/…/compile.ts• L86-137 packages/…/ast.ts• L223-228 packages/…/ast.ts• L230-705 packages/…/ast.ts• L1771-2018 packages/…/index.ts• L878-905

Incremental build behavior

The compiler separates one-time CSS preparation from repeated candidate builds. Preparation creates the design system and transforms directives. Each build adds newly discovered valid candidates, regenerates the utility portion when needed, and optimizes the complete CSS tree.

The incremental path compiles and sorts only new candidates. It caches each utility after optimization and selector flattening, then merges those cached results with the rest of the stylesheet. It falls back to the full build when the utility structure cannot be safely handled by this path, so the output remains equivalent.

This model supports watch mode and editor workflows that discover class names over time. A build can reuse the prior result when no candidate or external theme variable changed. A new valid candidate can change only the generated utility portion while authored CSS remains in place. Source-map requests still use the path that can record positions for the current output.

References: packages/…/incremental.ts• L8-30 packages/…/incremental.ts• L58-184 packages/…/incremental.ts• L184-295 packages/…/index.ts• L754-855

Change checklist

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

  • Changes to the package export map must keep the root compiler contract aligned with the public CSS entrypoint names.
  • Changes to @tailwind utilities processing must preserve the link between candidate discovery and the generated utility node.
  • Changes to CSS parsing must preserve the tree shape expected by directive expansion, nesting, source maps, and generated CSS.
  • Changes to custom-property or string boundary handling must keep semicolons and braces inside valid CSS values from splitting declarations.
  • Changes to source tracking or parser error locations must preserve file, line, and column data for compiler diagnostics.
  • Changes to candidate parsing or arbitrary-value validation must keep accepted class syntax aligned with utility and variant matching.
  • Changes to candidate normalization must preserve declaration signatures, theme-variable use, variant order, important state, and @scope behavior.
  • Changes to CSS escape and unescape rules must preserve candidate matching for escaped punctuation and malformed code points.
  • Changes to selector parsing or nesting must preserve &, relative selectors inside @scope, selector-list, and @scope semantics for both authored and generated rules.
  • Changes to theme registration must account for both emitted theme variables and values resolved while compiling candidates.
  • Changes to incremental utility caching must preserve the same sort order, at-rule merging, declaration deduplication, and keyframe tracking as the full build.
  • Changes to incremental build state must preserve reuse for unchanged candidate sets and regeneration for new candidates or used theme variables.

Important failure modes

TriggerConsequenceGuard
A candidate cannot be parsed or compiledThe candidate is marked invalid and produces no CSSKeep candidate syntax aligned with registered utilities and variants
An arbitrary value has unbalanced delimiters, a top-level semicolon, or an unsafe comment boundaryThe candidate is rejected before rule generationKeep arbitrary values valid as one CSS value
Stacked variants would create an overly large flattened selectorThe candidate produces no CSSKeep variant stacks and arbitrary selectors within practical bounds
Authored CSS has an unbalanced block or unterminated stringParsing stops with a syntax error and no complete transformation is availableKeep blocks and strings balanced
An incomplete custom property has no valueParsing stops with a syntax errorGive each custom property a value
A custom-property value contains an unbalanced function or block at the input endThe value is not emitted as a complete declarationClose the value's delimiters
An escaped identifier contains an invalid code pointThe escape is decoded to the replacement character and may not match the intended theme variableUse valid CSS identifier escapes
A scoped variant is reduced to the signature of an unscoped or empty variantCandidate normalization can rewrite the class to a variant with different scope behaviorInclude generated @scope rules when comparing variant signatures
@tailwind utilities is missing when utility generation is expectedAuthored CSS is returned without the generated utility sectionInclude the utility entrypoint or an equivalent directive
A custom variant depends on itself through another custom variantCompilation stops with a circular dependency errorKeep custom variant dependencies acyclic
A theme value cannot resolveThe affected candidate produces no ruleDefine the theme value or use a valid arbitrary value
A selector or nesting form cannot produce a live ruleThe affected declarations are droppedUse valid selector nesting and compatible variant combinations
Incremental caching cannot represent a utility or its wrappersThe compiler switches to the full build pathKeep incremental output equivalent to the full AST path

Key files

FileWhy to read it
packages/…/index.tsMain public compiler boundary and CSS transformation flow
packages/…/css-parser.tsAuthored CSS parsing and source-aware syntax errors
packages/…/css-parser.test.tsParser guarantees for comments, declarations, custom properties, nesting, at-rules, and errors
packages/…/compile.tsCandidate validation, rule generation, variant application, and output order
packages/…/incremental.tsIncremental utility compilation, caching, merging, and full-build fallback
packages/…/design-system.tsShared theme, utility, variant, cache, and tooling context
packages/…/candidate.tsCandidate and variant shapes plus class-name parsing
packages/…/is-valid-arbitrary.tsSafety checks for arbitrary values before CSS decoding
packages/…/canonicalize-candidates.tsStable candidate normalization, variant signatures, and safe utility replacement
packages/…/ast.tsCSS tree optimization, nesting, scope handling, theme pruning, caching, and final structure
packages/…/selector-parser.tsStructured selector parsing used by nesting and variant handling
packages/…/utilities.tsCore utility rules and their connection to theme values
packages/…/index.cssFull public CSS composition and layer order
packages/…/package.jsonPublic compiler and CSS export paths
packages/…/utilities.cssPublic utility-generation entrypoint