Tailwind custom selector trick

Wasn’t sure where to write this, but wanted to remember it.

<div class="[&>p]:max-w-[40rem]"></div>

This is a way to create a tailwind class that applies to a custom select [&>p]. (If I recall correctly, this is “the <p> elements that are the direct children of this element.”)

There’s some documentation about Arbitrary Variants, which reveals you can use _ for spaces:

<div class="[&_p]:max-w-[40rem]"></div>

They link to their addVariant plugin API for the syntax, but I can’t immediately see it there. I’d like to know if I can apply it to multiple elements as children (e.g., h1, h2, h3). Maybe it’s common CSS knowledge. ChatGPT was confused about it, at least.

The CSS selector you’ve written seems to be a bit incorrect as the “&” symbol is used in CSS pre-processors like Sass or Less, not in pure CSS.

In Sass or Less, the “&” symbol refers to the parent selector. However, the “&>h1” selector is not valid even in these pre-processors.

gpt-4

🤷‍♂️