- Instant help with your CSS coding problems

Select the nth child in TailwindCSS

Question:
How to select the nth child in TailwindCSS?
Answer:
<table class="w-80">
    <tbody class="[&>*:nth-child(odd)]:bg-teal-200">
        <tr><td>Line - 1</td></tr>
        <tr><td>Line - 2</td></tr>
        <tr><td>Line - 3</td></tr>
        <tr><td>Line - 4</td></tr>
        <tr><td>Line - 5</td></tr>
    </tbody>
</table>
Description:

To access the nth child using TailwindCSS you can use the arbitrary variants, that are format strings that represent the selector, wrapped in square brackets. You can write custom selector modifiers directly in your HTML. Just like arbitrary values let you use custom values with your utility classes, arbitrary variants let you write custom selector modifiers directly in your HTML:

For example to create a zebra styled table you can use the arbitrary variant: [&>*:nth-child(odd)]  

Where:

  • The ampersand & is used to reference the parent selector.
  • The greater than symbol > is used to select direct children of an element.
  • The asterisk * is used to select all descendants of an element.

So the following code:

<table class="w-80">
    <tbody class="[&>*:nth-child(odd)]:bg-teal-200">
        <tr><td>Line - 1</td></tr>
        <tr><td>Line - 2</td></tr>
        <tr><td>Line - 3</td></tr>
        <tr><td>Line - 4</td></tr>
        <tr><td>Line - 5</td></tr>
    </tbody>
</table>

Results the following output:

nth child zebra table

Share "How to select the nth child in TailwindCSS?"
Interesting things
OpanAi's ChatGPT