I recently encountered a situation where I needed to target the “nth element” in a list. I had a list of items, and I wanted to apply a different background color to every other row, e.g., all the even rows would have a white background, and all the odd rows would have a light grey background. The HTML looked along the lines of:
<div>
<div>First row of the list</div>
<div>Second row of the list</div>
<div>Third row of the list</div>
<div>Fourth row of the list</div>
<div>Fifth row of the list</div>
</div>
In vanilla CSS, you could achieve this using nth-child
selector. But Tailwind doesn’t have an nth-child
variant. So how do you target the “nth element” in Tailwind?
Tailwind has a concept of “arbitrary variants, ” allowing you to create custom variants. So I could implement the same functionality using the following Tailwind classes on the parent element:
<!--
========================================
Classes to apply on parent element
========================================
[&>*:nth-child(odd)]:bg-gray-300
[&>*:nth-child(even)]:bg-white
-->
<div class="[&>*:nth-child(odd)]:bg-gray-300 [&>*:nth-child(even)]:bg-white">
<div>First row of the list</div>
<div>Second row of the list</div>
<div>Third row of the list</div>
<div>Fourth row of the list</div>
<div>Fifth row of the list</div>
</div>
To make the above a bit less verbose you can also create a custom variant in your Tailwind config file using the addVariant
API. Have a look at the tailwind documentation for more information on how to use arbitrary variants.