Skip to content

Custom Tailwind Variants

Tailwind CSS allows you to create custom variants via @custom-variant. This lets you define reusable selectors — like hover: or focus: — tailored to your project's specific needs.

Defining Custom Variants

Custom variants are defined in a dedicated file:

css
/* styles/variants/variants.css */

@custom-variant hoverfocus (&:hover, &:focus);
@custom-variant dataactive (&[data-active]:not([data-active="false"]));
@custom-variant opened (&[open]:not([open="false"]));

Usage

Use them in your markup just like any native Tailwind variant:

html
<button class="hoverfocus:text-primary">...</button>
<div class="opened:bg-primary">...</div>

When to Create a Custom Variant

  • When a selector is used repeatedly across multiple components
  • When the equivalent native Tailwind syntax would be too verbose

One-off selectors

For a one-off selector, you don't need to register anything — use Tailwind's arbitrary variant syntax directly in the markup:

html
<button class="[&:hover,&:focus]:text-primary">...</button>

As soon as you catch yourself repeating the same arbitrary variant, promote it to a @custom-variant — this is exactly what the Tailwind documentation recommends.