Targeting Children of nth-of-type in Tailwind CSS
3rd Nov 2024
How I applied different background colors to a child of list items in a sequence.
Using Tailwind CSS to Target Children Within a List of Items
While working on a recent project that utilized Tailwind CSS, I encountered a challenge: I wanted to apply different background colors to a <p>
element that was a child of an <li>
created from a .map
method, repeating the color pattern after the 4th item. I knew that the CSS :nth-of-type()
selector could accomplish this, but I wasn’t sure how to target a certain child element within that series of sibling elements using Tailwind CSS.
The :nth-of-type() CSS pseudo-class matches elements based on their position among siblings of the same type (tag name).
Exploring Tailwind Utilities
To solve this problem, I tried several strategies using Tailwind’s utilities. My goal was to find a clean and efficient way to apply these styles without writing custom CSS.
Discovering the Power of the Group Utility
After diving into the Tailwind CSS documentation and several other resources, I discovered the group modifier, which allows for targeting child elements based on the state of their parent. By adding the group
class to my list item, I could effectively utilize nth-child
to style the specific item in the list item based on what number in the sequence it’s parent (the <li>
item) is, repeating the pattern after every 4th item.
Here’s how I implemented this solution:
<ul class="mt-20">
{valuePropositions.map((valueProposition) => (
{/* Parent container with group class to enable targeting child elements */}
<li class="valueItem group [&:not(:first-child)]:mt-2.5">
<div class="relative flex rounded-xl pt-7 pb-6 bg-neutral justify-center items-center">
<h3 class="mb-0 text-lg text-beige font-sans font-bold">
{valueProposition.topic}
</h3>
<ChevronValueItem classes="absolute right-4" />
</div>
{/* Applying different background colors based on list item sequence */}
<p class="hidden rounded-b-xl pb-5 px-20 text-lg text-[#555a6e] group-[&:nth-of-type(4n+1)]:bg-blue-light group-[&:nth-of-type(4n+2)]:bg-coral-light group-[&:nth-of-type(4n+3)]:bg-green-light group-[&:nth-of-type(4n+4)]:bg-white">
{valueProposition.valueProposition}
</p>
</li>
))}
</ul>
Achieving Efficient, Pattern-Based Styling with Tailwind
This solution is relevant for developers who want to leverage Tailwind CSS while still achieving more complex styling scenarios. It demonstrates the flexibility of Tailwind and how it can integrate with JavaScript functionalities like the .map
method.
The result: