Posted Wednesday, October 11, 2023
A Tailwind Modifier to Target Child Elements
Reduce class clutter with this technique
We can target child elements from a parent element using the arbitrary selector:
[&>*]
: we can select all direct child elements to add vertical padding[&>*:not(:last-child)]
: we can select all direct child elements, except the last child, to add a bottom border
- Lorem ipsum dolor sit amet.
- Est qui laudantium quo repudiandae.
- Quod soluta labore suscipit necessitatibus.
- Animi eaque voluptate culpa est.
<ul class="[&>*]:py-4 [&>*:not(:last-child)]:border-b">
<li>Lorem ipsum dolor sit amet.</li>
<li>Est qui laudantium quo repudiandae.</li>
<li>Quod soluta labore suscipit necessitatibus.</li>
<li>Animi eaque voluptate culpa est.</li>
</ul>
You can also create a Tailwind plugin to create shortcuts for these selectors: https://tailwindcss.com/docs/hover-focus-and-other-states#creating-a-plugin