Apply a style to a children with Tailwind

By

Learn how to apply a Tailwind style to all child elements of an element using the [&>*] arbitrary variant, or the newer *: variant in Tailwind 3.4.

~~~

UPDATE: use *: as of Tailwind 3.4

To style all the direct children of an element with Tailwind, you have two options: the [&>*] arbitrary variant, or the shorter *: variant if you’re on Tailwind 3.4 or newer.

It doesn’t happen often, but sometimes I wonder, how do I apply a style to a child element, with Tailwind?

The next time this happens, I’ll have this blog post explain it to me.

The arbitrary variant

You can use this class name to apply the bg-gray-300 class (for example) to all child elements of the current element:

[&>*]:bg-gray-300

Like this:

<ul class="[&>*]:bg-gray-300">
  <li>Astro</li>
  <li>HTMX</li>
  <li>Alpine.js</li>
</ul>

How does it work? Inside the square brackets you write a CSS selector. The & stands for the current element, and > * is the CSS child combinator, which matches every direct child. Tailwind generates the equivalent of this CSS:

ul > * {
  background-color: #d1d5db;
}

Every li gets the gray background, and you only wrote one class on the parent. Handy when the children come from a loop, or from markdown you don’t control.

The *: variant

Tailwind 3.4 added a shorthand for this exact need:

<ul class="*:bg-gray-300">
  <li>Astro</li>
  <li>HTMX</li>
  <li>Alpine.js</li>
</ul>

Same result, less typing. If your project is on 3.4 or later, use this one.

Direct children only

Both variants target direct children. Grandchildren are not affected. If you need to reach all descendants, use an underscore instead of >:

[&_*]:bg-gray-300

In arbitrary variants, the underscore stands for a space. So this generates the descendant selector, which matches every element nested inside, at any depth.

One thing to watch out for

You can’t override the style from the child. Say one li needs a white background, so you add bg-white to it. It won’t win against the parent’s *:bg-gray-300, because of how the generated child selector is applied. Tailwind’s docs call this out too.

The fix: when children need different styles, skip the child variant and put the classes on each child directly. The child variant is for the case where all children get the same treatment.

Tagged: CSS · All topics
~~~

Related posts about css: