Home > database >  Nested Brackets and Ampersand usage in Tailwind UI examples
Nested Brackets and Ampersand usage in Tailwind UI examples

Time:09-10

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).

CodePudding user response:

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 >
  <div ></div>
</div>

is conceptually like:

<div >
  <div ></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 ></div><div ></div>

is conceptually like:

<div ></div><div ></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 ></div>

is conceptually like:

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

Hopefully this example makes the nested brackets clear.

  • Related