Sub topic 14
Arbitrary variants for custom conditions
What this chapter assumes
You should already know the built-in variants from earlier chapters: hover:, focus-visible:, group-hover:, peer-invalid:, and stacking such as dark:hover:. You should also be comfortable reading CSS selectors and @media rules. This chapter covers what to do when no built-in variant matches the condition you need.
Why arbitrary variants exist
Tailwind ships variants for the most common conditions. Sooner or later you need one it doesn't ship. Examples are "the third child", "any link inside this article", or "only when the browser supports grid".
An arbitrary variant lets you write the condition inline. You put a selector or an at-rule in square brackets and use it as a prefix, like any other variant:
<li class="[&:nth-child(3)]:underline">Third item</li>Tailwind reads the text in brackets, builds the matching CSS, and applies the utility only under that condition. You get the same result as writing a CSS rule by hand, without leaving the HTML.
Selector variants with `&`
In a selector variant, & stands for "the element that carries this class". Everything else in the brackets is ordinary CSS around it.
| Class | Generated condition | Meaning |
|---|---|---|
| `[&:nth-child(3)]:underline` | `.x:nth-child(3)` | The element, only if it is the third child |
| `[&_p]:mt-4` | `.x p` | Every `p` inside the element |
| `[&>li]:py-1` | `.x > li` | Direct `li` children |
| `[&+&]:mt-2` | `.x + .x` | An element right after another with the same class |
| `[.dark_&]:bg-black` | `.dark .x` | The element when an ancestor has the class `dark` |
Here .x stands for the escaped class name that Tailwind generates. Placing & at the end, as in [.dark_&], turns the selector into an ancestor test.
Underscores stand for spaces
Class names cannot contain spaces. Inside brackets, Tailwind therefore converts each underscore to a space. [&_p] becomes & p, a descendant selector. If you need a literal underscore, escape it with a backslash.
Styling children from the parent
A selector variant on a parent can replace a pile of repeated classes on its children. This is useful for content you don't control, such as rendered Markdown:
<article class="[&_p]:mb-4 [&_a]:text-indigo-600 [&_a:hover]:underline">
<p>Tailwind can style <a href="#">links</a> without classes on them.</p>
<p>The second paragraph gets the same margin.</p>
</article>Note that [&_a:hover]:underline puts the pseudo-class inside the brackets. The :hover applies to the link, not to the article.
At-rule variants
If the bracket text starts with @, Tailwind treats it as an at-rule. This covers @media, @supports, and @container:
<div class="block [@supports(display:grid)]:grid [@supports(display:grid)]:grid-cols-3">
Three columns where grid is supported.
</div>You can also combine an at-rule with a selector by putting & in braces after it. The following button is dimmed by default and brightens on hover only on devices that really have hover:
<button class="opacity-50 [@media(any-hover:hover){&:hover}]:opacity-100">
Run
</button>This is the pattern to reach for with hover on touch devices. Without the media query, a tap can leave the hover style stuck until the user taps elsewhere.
Arbitrary values inside group and peer
The group-* and peer-* variants accept brackets too. The bracket holds a selector that is tested against the marked parent or sibling, not against the element itself.
A group driven by a class
The panel below opens when JavaScript toggles an is-open class on the parent. No built-in variant knows about is-open, so the bracket supplies it:
<div id="panel" class="group rounded border p-4">
<button id="toggle" class="font-semibold">Details</button>
<div class="hidden group-[.is-open]:block">
Extra information appears here.
</div>
</div>
<script>
document.querySelector("#toggle").addEventListener("click", () => {
document.querySelector("#panel").classList.toggle("is-open");
});
</script>group-[.is-open]:block means "when the nearest group ancestor matches .is-open, set display: block".
A peer driven by a pseudo-class
A floating label is a classic case. The input is marked peer, and the label after it reacts when the input is not empty:
<div class="relative">
<input
id="email"
type="email"
placeholder=" "
class="peer w-full rounded border px-3 pt-5 pb-1"
/>
<label
for="email"
class="absolute left-3 top-3.5 text-slate-500 transition-all peer-focus:top-1 peer-focus:text-xs peer-[:not(:placeholder-shown)]:top-1 peer-[:not(:placeholder-shown)]:text-xs"
>
Email
</label>
</div>The placeholder is a single space, so :placeholder-shown is true while the field is empty. peer-[:not(:placeholder-shown)]: keeps the label small after the user types and then leaves the field. As with every peer variant, the label must come after the input in the DOM.
Attribute variants: `data-` and `aria-`
Before you write a bracket selector for an attribute, check whether data-[...] or aria-[...] fits. These read better and match how component libraries expose state:
<button
data-state="open"
class="rounded px-3 py-2 data-[state=open]:bg-slate-200 data-[state=open]:font-semibold"
>
Menu
</button>
<th aria-sort="ascending" class="px-3 py-2 aria-[sort=ascending]:bg-indigo-50">
Name
</th>Headless UI libraries often set attributes like data-state="open" for you. Matching those attributes keeps your styling in sync with the component's state without any extra JavaScript.
Stacking with arbitrary variants
Arbitrary variants combine with other variants in the same way as built-in ones. Each prefix adds one more condition:
<li class="md:[&:nth-child(odd)]:bg-slate-50 dark:[&:nth-child(odd)]:bg-slate-800">
Row
</li>The first class applies to odd rows at the md breakpoint and above. The second applies to odd rows in dark mode. Stacking has limits. A long chain of brackets is hard to read and hard to debug, which is the signal to move the condition somewhere else (see the last section).
The decision flow below summarizes how to pick a variant form.
Common errors
- Dynamic class names. Tailwind finds classes by scanning your source for complete strings. Writing `
[&:nth-child(${n})]:underline` produces nothing, because the full class never appears in the source. List every full class you need, or choose between complete strings. - Spaces instead of underscores.
[&_p]:mt-4works.[& p]:mt-4splits into two classes and does nothing. - Missing
&. A selector variant needs&to say where the element goes. Without it, the bracket text is not a valid variant. - Wrong target in
group-[...]. The bracket selector is tested against the group element.group-[.is-open]needsis-openon thegroupelement, not on the child you are styling. - Peer order.
peer-[...]only affects later siblings of the marked element, the same as built-in peer variants. - Over-specific selectors.
[&_div>ul_li]:...ties the markup structure to a class on a distant ancestor. A small HTML change can break it silently.
When to promote to a custom variant
An inline bracket is the right tool for a condition used once or twice. If you paste the same bracket across many files, name it. In Tailwind CSS v4 you declare a custom variant in your stylesheet:
@import "tailwindcss";
@custom-variant theme-midnight (&:where([data-theme="midnight"], [data-theme="midnight"] *));You can then write theme-midnight:bg-slate-900 anywhere in your markup. In Tailwind v3 you do the same with the addVariant function in a plugin. Naming the variant also gives you one place to fix the selector later.
Keep the decision simple. Use a built-in variant when one exists. Use an attribute variant when the state is an attribute. Write a bracket when you have a one-off condition. Define a custom variant when the bracket repeats.
Exercise
A card has the class group and a child with the class hidden group-[.is-selected]:block. The card never shows the child, even though JavaScript adds is-selected to the card's inner heading element. What is wrong, and how do you fix it?
Show answer
The group-[.is-selected] selector is tested against the element marked group, which is the card, not the heading. Add the is-selected class to the card (the group element) instead of the heading. Alternatively, move the group class to the heading and keep the hidden child inside it.
Exercise
Write a single class that makes every direct li child of a ul use py-2, only when the pointer device supports hover, and gives the li the bg-slate-100 background when hovered, placed on the ul.
Show answer
[@media(any-hover:hover){&>li:hover}]:bg-slate-100 for the hover background, together with [&>li]:py-2 for the padding. The first class combines an at-rule with a selector by placing & in braces after the at-rule. Underscores are not needed here because neither selector contains a space.
Exercise
Why does ` [&:nth-child(${index})]:font-bold ` in a template string fail to style anything?
Show answer
Tailwind scans source files for complete class strings at build time. The string above is only complete at runtime, so Tailwind never sees the class and generates no CSS for it. Write out each full class you need, such as [&:nth-child(2)]:font-bold, and choose between them in code.