Sub topic 3
Arbitrary Variants for Custom Selectors and At-Rules
Assume you know basic CSS selectors, custom properties, Tailwind utilities, and variant prefixes such as hover: and md:. Tailwind usually gives you a utility or variant for common cases. Arbitrary variants handle less common selectors and conditions.
Custom Selectors and At-Rules
An arbitrary variant is a selector or at-rule in square brackets before a utility. The & character represents the element that owns the class.
<ul class="[&>li:nth-child(odd)]:bg-gray-100">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>Tailwind generates a rule that applies the background utility to odd, direct-child list items. Underscores represent spaces when a selector or value needs them.
You can also use an at-rule. This example applies grid only when the browser supports CSS Grid:
<ul class="[@supports(display:grid)]:grid">
<li>One</li>
<li>Two</li>
</ul>Arbitrary variants can combine with responsive and state variants:
<div class="md:hover:[&>a]:underline">
<a href="/docs">Documentation</a>
</div>This targets direct child links when the viewport reaches the md breakpoint and the element is hovered.
Why Dynamic Class Names Fail
Tailwind scans source files as plain text. It detects complete class names, but it does not execute string interpolation.
// Tailwind cannot detect the complete class name.
const broken = `w-[${width}px]`;
// Every possible class appears literally in the source.
const widths = {
narrow: "w-[240px]",
wide: "w-[480px]",
};
const working = widths[size];Use a complete class map when values come from known choices. For user-controlled values, use an inline style or a CSS custom property instead of constructing a class name.
Arbitrary Values or Theme Values?
Use an arbitrary value for a one-off design exception. Add a theme value when the value is reused, represents a design decision, or needs one shared name.
| Situation | Better choice |
|---|---|
| One component needs `w-[317px]` | Arbitrary value |
| Several components use the same spacing | Theme value |
| A custom selector has no built-in variant | Arbitrary variant |
Theme values improve consistency and make later changes easier. Arbitrary variants are useful when the selector is local and unlikely to become part of the design system.
Exercise
Why does w-[${width}px] fail, and what is a safe alternative for a fixed set of widths?
Show answer
Tailwind cannot see the complete class name during scanning. Use a map containing complete class names, such as { narrow: "w-[240px]" }.