Sub topic 8
Arbitrary variants for custom selectors and at-rules
This chapter covers arbitrary variants, the third use of square brackets in Tailwind CSS. Arbitrary values change what a utility sets. Arbitrary properties add a declaration that has no utility. Arbitrary variants change when a utility applies. You write a selector or an at-rule inside the brackets, and Tailwind wraps the utility in it.
It assumes you know the following:
- Basic CSS selectors, including combinators (
>, descendant space) and pseudo-classes such as:nth-child(). - At-rules such as
@mediaand@supports. - Tailwind variant prefixes such as
hover:andmd:. - The earlier chapters on square-bracket values, underscores for spaces, and static class detection.
What an arbitrary variant is
A built-in variant like hover: is a name that Tailwind maps to a selector. An arbitrary variant skips the name. You write the selector or at-rule yourself, in square brackets, followed by a colon and then the utility:
<ul class="[&>li:nth-child(odd)]:bg-gray-100 [@supports(display:grid)]:grid">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>This class list contains two arbitrary variants:
[&>li:nth-child(odd)]:bg-gray-100is a selector variant. The&stands for the element that carries the class. The utilitybg-gray-100applies to the oddlichildren of that element.[@supports(display:grid)]:gridis an at-rule variant. It starts with@, so Tailwind wraps the utility in that at-rule. The element becomes a grid only in browsers that support grid.
The generated CSS looks roughly like this (class names are escaped in the real output):
.\[\&\>li\:nth-child\(odd\)\]\:bg-gray-100 > li:nth-child(odd) {
background-color: var(--color-gray-100);
}
@supports (display: grid) {
.\[\@supports\(display\:grid\)\]\:grid {
display: grid;
}
}The class name still ends up on the element you wrote it on. For a selector variant, & is replaced by that class selector, and whatever you wrote around & becomes part of the full selector.
How Tailwind reads the bracket
Tailwind splits a class at the last unbracketed colon. Everything before it is variants, and the remainder is the utility. A variant that is wrapped in square brackets is treated as arbitrary. Tailwind then looks at the first character inside the brackets.
Two consequences follow:
- A selector variant must contain
&. Without it, Tailwind has no way to know where the element sits in the selector, so it ignores the class. - Colons inside the brackets are fine, because only the last colon outside the brackets separates variant from utility. That is why
[&:nth-child(3)]:underlineworks.
Selector variants
Descendants and children
In a selector, a space is a descendant combinator. A space inside a class attribute would end the class, so you write an underscore instead. Tailwind turns it into a space, exactly as in arbitrary values.
<article class="[&_p]:mt-4 [&_a]:underline [&>h2]:text-xl">
<h2>Title</h2>
<p>Body with a <a href="/docs">link</a>.</p>
</article>[&_p]:mt-4becomes.cls p. It matches everypinside the article at any depth.[&>h2]:text-xlbecomes.cls>h2. It matches only direct children. The>needs no spaces.
This pattern is useful when you cannot add classes to the inner elements. A common case is HTML that comes from a CMS or a Markdown renderer.
Pseudo-classes and attribute selectors
Anything that fits after & works:
<button
class="[&:nth-child(3)]:underline [&[data-state=open]]:rotate-180 [&:not(:last-child)]:mb-2"
>
Toggle
</button>For [&[data-state=open]], the outer brackets belong to Tailwind. The inner brackets belong to the CSS attribute selector. Tailwind matches the brackets in pairs, so nesting works.
Check whether a built-in variant already covers your case before writing one by hand. data-[state=open]:rotate-180, has-[:checked]:bg-blue-50 and first:, last:, odd: and even: express the same ideas with less noise. Direct-child styling has a built-in form too. *:p-2 styles every direct child. Which of these exist depends on your Tailwind version, so check its documentation.
Context from an ancestor
Putting & at the end of the selector lets you react to something above the element. This is the usual way to style by a class on html or body:
<div class="bg-white [.dark_&]:bg-slate-900 [body.compact_&]:p-2">
Card
</div>[.dark_&]:bg-slate-900 produces .dark .cls. The element must therefore be a descendant of an element with class dark.
Stacking with other variants
An arbitrary variant stacks with built-in variants in the same way built-in variants stack with each other:
<ul class="md:[&>li]:flex hover:[&_a]:underline">
<li><a href="/a">A</a></li>
</ul>Here md:[&>li]:flex applies only at the md breakpoint and only to direct li children. In hover:[&_a]:underline, the hover: condition applies to the ul, not to the links. If you want links to underline when hovered, write the pseudo-class inside the brackets as [&_a:hover]:underline.
Tailwind has changed how it orders stacked variants between major versions. Older versions applied them right to left, and Tailwind v4 applies them left to right. For common combinations like those above the result is identical. When you stack two selector variants and the output looks wrong, inspect the generated CSS and swap the order.
At-rule variants
When the bracket content starts with @, Tailwind wraps the utility rule in that at-rule.
<div class="[@supports(display:grid)]:grid [@media(min-width:900px)]:flex-row flex flex-col">
...
</div>The condition after the at-rule name is written without spaces, so @supports(display:grid) has no space before the parenthesis. If you need a space inside, for example in not (display:grid), use an underscore. Tailwind treats it the same way as in any other arbitrary value.
For a viewport size that is not in your theme, an at-rule variant is a handy one-off: [@media(min-width:900px)]:flex-row. If you use the same width in several places, define a breakpoint in the theme instead. The last section covers that.
Combining an at-rule and a selector
Sometimes you need both: a media query and a selector. Put the selector in braces after the at-rule:
<a class="opacity-70 [@media(any-hover:hover){&:hover}]:opacity-100" href="/">
Link
</a>This generates:
@media (any-hover: hover) {
.cls:hover {
opacity: 1;
}
}The result is a hover effect that only applies on devices with a real hover input. Touch devices keep the base opacity and avoid a stuck hover state after a tap.
Summary of forms
| You write | Generated shape |
|---|---|
| `[&>li]:p-2` | `.cls>li { padding... }` |
| `[&_p]:p-2` | `.cls p { padding... }` |
| `[&:nth-child(3)]:p-2` | `.cls:nth-child(3) { padding... }` |
| `[.dark_&]:p-2` | `.dark .cls { padding... }` |
| `[@supports(display:grid)]:grid` | `@supports (display:grid) { .cls { display:grid } }` |
| `[@media(any-hover:hover){&:hover}]:p-2` | `@media (any-hover:hover) { .cls:hover { padding... } }` |
Gotchas
Specificity is higher than you expect
A selector variant adds a combinator or pseudo-class, so its rule is more specific than a plain utility. Consider this markup:
<div class="[&_p]:text-red-600">
<p class="text-blue-600">Which color?</p>
</div>The first rule is .cls p, with specificity (0,1,1). The second is .text-blue-600, with specificity (0,1,0). The paragraph is red. Utility order in the stylesheet does not matter here, because specificity decides first. If you want a child to override the parent's [&_p] rule, you need a variant of the same strength on the child, or you can avoid the parent-driven style for that element.
In Tailwind v4 you can write the selector with :where() for zero specificity, such as [&:where(.dark_*)]:bg-black. Use it when you want the rule to be easy to override.
Selectors that need a space or a quote
- Use
_for spaces, as shown. To write a literal underscore, escape it with a backslash:\_. - Quotes inside an HTML
classattribute collide with the attribute's own quotes. Use single quotes inside the brackets when the attribute uses double quotes, or avoid quoted values by choosing unquoted attribute values such as[data-state=open].
Long names hide intent
A class like [&:not(:first-child):not(:last-child)>a:hover]:underline is hard to read and easy to get wrong. If a selector grows past a short expression, that is a sign to name it, as the last section describes.
Static detection still applies
Tailwind reads your source files as plain text and looks for complete class names. An arbitrary variant is subject to the same rule. This code never produces CSS:
// Not detected: the selector is assembled at runtime
const broken = `[&_${tag}]:mt-4`;
// Detected: each class name appears in full in the source
const rules = {
p: "[&_p]:mt-4",
li: "[&_li]:mt-4",
};
const working = rules[tag];The first line produces [&_p]:mt-4 at runtime, but Tailwind never saw that string in your files, so the CSS rule does not exist. The lookup map keeps every class visible to the scanner.
Naming a variant you use often
Arbitrary variants are for one-off conditions. When you repeat the same bracket across many elements, define a named variant. In Tailwind v4, you do it in your CSS with @custom-variant:
@import "tailwindcss";
@custom-variant theme-midnight (&:where([data-theme="midnight"] *));You can then write the class theme-midnight:bg-black, and it behaves like a built-in variant. It works with stacking, for example md:theme-midnight:bg-black. In Tailwind v3, the same thing is done with addVariant() in a plugin in tailwind.config.js.
Choosing between the options
Use the table to pick a tool for the condition you need.
| Situation | Better choice |
|---|---|
| A built-in variant already expresses the condition (`hover:`, `data-[...]:`, `has-[...]:`) | The built-in variant |
| One element needs a one-off selector or at-rule | An arbitrary variant |
| Styling elements you cannot add classes to, such as CMS output | `[&_tag]:` arbitrary variants on the wrapper, or a small CSS rule for the content |
| The same bracket appears in many places | A named custom variant |
| A breakpoint or condition is part of your design system | A theme value or custom variant |
The cost of an arbitrary variant is readability and repetition. The cost of a named one is a small amount of setup. A good threshold is repetition: the third time you write the same bracket, name it.
Exercise
A page has a div with the class [&_p]:text-red-600. Inside it is <p class="text-blue-600">. Why is the paragraph red, and what is one way to make it blue?
Show answer
[&_p]:text-red-600 generates .cls p, which has specificity (0,1,1). .text-blue-600 has specificity (0,1,0), so the red rule wins regardless of source order. One fix is to give the paragraph an arbitrary variant of equal strength that targets itself, for example [&:is(p)]:text-blue-600. A simpler fix is to remove [&_p]:text-red-600 from the wrapper and put text-red-600 on the paragraphs that need it.
Exercise
Write a class that makes an element's direct li children bold only at viewport widths of at least 800px, using one arbitrary variant that combines the media query and the selector. Then write the CSS that Tailwind generates.
Show answer
Class: [@media(min-width:800px){&>li}]:font-bold. Generated CSS: @media (min-width: 800px) { .cls>li { font-weight: 700; } }. The selector goes in braces after the at-rule, and & stands for the element.
Exercise
A component builds ` [&_${tag}]:mt-4 ` from a prop, and no styles appear. Explain why and fix it.
Show answer
Tailwind scans source files as plain text and only generates CSS for class names that appear in full. The template string is never a complete class name in the source. Replace it with a map of complete strings, such as { p: "[&_p]:mt-4", li: "[&_li]:mt-4" }, and look up the entry for the prop.