Nested Brackets and Ampersand usage in Tailwind UI examples
Asked Answered
R

1

6

Can somebody help translate bracket usage in Tailwind.css?

In Example 1: what does [&_*] mean?
In Example 2: what does the nested bracket combined with _& mean?

Example 1:

    document.documentElement.classList.add('[&_*]:!transition-none')

Example 2:

<LightIcon className="hidden h-4 w-4 fill-slate-400 [:not(.dark)[data-theme=system]_&]:block" />

The closest I can get is the [] refers to attribute selection (in general) for .css and the Ampersand in is used by PostCSS processing in "normal" SASS nesting rules (as defined by tailwind's default nesting declaration support provided by postcss-nested).

Reeves answered 9/9, 2022 at 18:8 Comment(0)
F
16

What you are seeing is the usage of Tailwind's arbitrary variants feature.

Inside the square brackets is a CSS selector (or media query, I won't be talking about that here), with the ampersand (&) a substitute for the element that the class is being applied to. The nested brackets are attribute selectors, like with standard CSS selectors, as you correctly inferred in your Stacked Overflow question. Underscore is used instead of spaces in a CSS selector.

To give a few examples:

<div class="foo">
  <div class="[.foo_&]:text-white"></div>
</div>

is conceptually like:

<div class="foo">
  <div class="bar"></div>
</div>
<style>
/**
 * .foo .bar
 *   ↓
 * .foo &
 *   ↓
 * .foo_&
 */
.foo .bar {
  color: white;
}
</style>

With .bar now &, since .bar is the element we are applying the class/style to.


Another example:

<div class="foo"></div><div class="[.foo+&]:text-white"></div>

is conceptually like:

<div class="foo"></div><div class="bar"></div>
<style>
/**
 * .foo + .bar
 *   ↓
 * .foo + &
 *   ↓
 * .foo+&
 */
.foo + .bar {
  color: white;
}
</style>

The + grammar in CSS selectors does not strictly need spaces around it, so we can remove them for a more concise arbitrary variant syntax.


<div data-foo class="[&[data-foo]]:text-white"></div>

is conceptually like:

<div data-foo class="bar"></div>
<style>
/**
 * .bar[data-foo]
 *   ↓
 *    &[data-foo]
 */
.bar[data-foo] {
  color: white;
}
</style>

Hopefully this example makes the nested brackets clear.

Fallow answered 9/9, 2022 at 22:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.