0
0
Tailwindmarkup~3 mins

Why Arbitrary variants for custom selectors in Tailwind? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to style exactly what you want without leaving your HTML!

The Scenario

Imagine you want to style a button only when it is inside a special container or when a certain attribute is present, so you write CSS selectors by hand for each case.

The Problem

Writing and maintaining these custom selectors manually is slow and error-prone. Every time the HTML structure changes, you must update your CSS selectors, which can break styles or cause unexpected results.

The Solution

Arbitrary variants let you write any custom CSS selector directly inside Tailwind classes, so you can target exactly what you want without leaving your HTML or writing separate CSS files.

Before vs After
Before
.special-container button { background-color: blue; }
[data-state='open'] > .menu { display: block; }
After
[.special-container_&]:bg-blue-500
[[data-state='open']_>_.menu]:block
What It Enables

You can create precise, complex style rules inline with your HTML, making your code easier to read, maintain, and adapt.

Real Life Example

For example, you want a card to have a shadow only when it is inside a modal with a certain class, so you use an arbitrary variant to apply the shadow only in that context.

Key Takeaways

Manual CSS selectors are hard to maintain and update.

Arbitrary variants let you write custom selectors inside Tailwind classes.

This makes styling complex states and contexts easier and faster.