Tailwind CSS Course
Tailwind CSS
/
Advanced

Arbitrary Variants

Definition

Using square brackets to write custom CSS selectors directly inside your HTML class string, allowing you to target incredibly specific DOM relationships.

Explain Like I'm New

Tailwind has `hover:` and `focus:`. But what if you need to specifically target 'The third paragraph inside this div, but only when the div has the class `.is-active`'? You can literally write that CSS selector inside square brackets: `[&.is-active>p:nth-child(3)]:text-red-500`.

Real World Example

You are given a raw HTML string from a database containing an unordered list `<ul>`. You can't add classes to the `<li>` tags directly. You apply `[&>li]:text-blue-500` to the parent `div`, forcing all direct children `li` elements to be blue.

Common Use Cases

  • •Styling raw HTML
  • •Complex DOM targeting
  • •Third-party integrations

Interactive Example

Interview Questions

basic

  • In an arbitrary variant `[&>p]`, what does the `&` symbol represent?

intermediate

  • Why would you use `[&>li]:mt-4` on a parent `<ul>` instead of just putting `mt-4` on every `<li>` child?

Flash Cards

Question

What is &?

Click to reveal answer
Answer

It represents the CURRENT element that the class is placed on. It acts exactly like the CSS/Sass nesting selector.

Question

Why use it on parent?

Click to reveal answer
Answer

Usually, you SHOULD put the classes on the children. You only use arbitrary variants when you DO NOT CONTROL the child HTML (e.g., the `<li>` elements are being generated by a third-party Markdown library and you can't edit them).