- Published on
Using nth-child in Tailwind CSS on Parent Elements
- Authors
- Name
- Ripal & Zalak
Using nth-child in Tailwind CSS on Parent Elements
Tailwind CSS does not provide a built-in nth-child utility, but you can use arbitrary variants to apply styles dynamically. This is particularly useful for alternating table row colors or styling every odd/even child inside a parent element.
✅ Solution: Using nth-child with Tailwind’s Arbitrary Variants
You can apply nth-child(odd) and nth-child(even) styles to child elements dynamically by using Tailwind's arbitrary variants.
<table class=" [&>tbody>*:nth-child(even)]:bg-white [&>tbody>*:nth-child(odd)]:bg-gray-100">
<tr>
<td>Row 1</td>
<td>Data</td>
</tr>
<tr>
<td>Row 2</td>
<td>Data</td>
</tr>
<tr>
<td>Row 3</td>
<td>Data</td>
</tr>
</table>
🔥 How It Works:
&>tbody>*:nth-child(odd)]:bg-gray-100→ Applies a gray background to odd rows.&>tbody>*:nth-child(even)]:bg-white→ Applies a white background to even rows.- The
tbodyselector ensures that Tailwind applies styles correctly, avoiding issues with browser-inserted<tbody>elements.
🛠 Alternative Approach: Explicitly Defining <tbody>
Another way to avoid automatic browser insertion of <tbody> is to define it explicitly.
<table>
<tbody class=" [&>*:nth-child(even)]:bg-white [&>*:nth-child(odd)]:bg-gray-100">
<tr>
<td>Row 1</td>
<td>Data</td>
</tr>
<tr>
<td>Row 2</td>
<td>Data</td>
</tr>
<tr>
<td>Row 3</td>
<td>Data</td>
</tr>
</tbody>
</table>
By explicitly adding <tbody>, we avoid unexpected behavior from browsers inserting <tbody> automatically, which can affect Tailwind’s direct child selectors.
🚀 Using nth-child on Non-Table Elements
This approach isn’t limited to tables. You can use it with divs, lis, and other elements.
<div class=" p-4 [&>*:nth-child(even)]:bg-red-500 [&>*:nth-child(odd)]:bg-blue-500">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
</div>
🔥 Result:
- Odd items → Blue background
- Even items → Red background
❓ FAQs
1. Why doesn’t Tailwind have a built-in nth-child utility?
Tailwind’s core utilities focus on common styling needs. For advanced selectors like nth-child, arbitrary variants provide a flexible solution without bloating the framework.
2. Why do nth-child styles not apply to <tr> elements in Tailwind?
Most browsers automatically insert <tbody> into <table>, causing direct descendant selectors (&>*:nth-child()) to target <tbody> instead of <tr>. Using &>tbody>*:nth-child() fixes this.
3. Can I use this approach in Tailwind with React or Vue?
Yes! Tailwind’s arbitrary variants work in React, Vue, and other frameworks since they compile to CSS before rendering.
