Use nth-child(odd) css selector with Tailwind on parent element
P粉426780515
P粉426780515 2024-01-29 10:50:26
0
2
521

I'm trying to achieve the following:

<table>
  <tr class="odd:bg-white even:bg-slate-100">
    <td>name</td>
    <td>title1</td>
  </tr>
  <tr class="odd:bg-white even:bg-slate-100">
    <td>name</td>
    <td>title1</td>
  </tr>
  <tr class="odd:bg-white even:bg-slate-100">
    <td>name</td>
    <td>title1</td>
  </tr>
</table>

But instead of entering the css on each tr child tag, enter it once on the table tag.

Something like this: (BTW, I can't get it to work)

<table class="--odd:bg-white even:bg-slate-100 [&:nth-child(odd)]:bg-gray-400">
  <tr>
    <td>name</td>
    <td>title1</td>
  </tr>
  <tr>
    <td>name</td>
    <td>title1</td>
  </tr>
  <tr>
    <td>name</td>
    <td>title1</td>
  </tr>
</table>

Right now I'm doing something similar to implement it, but if possible I'd like to do it all with the Tailwind class

<style lang="postcss">
    div.plan-details :nth-child(odd) {
        @apply text-zinc-500;
    }
    div.plan-details :nth-child(even) {
        @apply text-zinc-900;
    }
</style>

Also tried this, but without success.

I have a tailwind game example with two examples

P粉426780515
P粉426780515

reply all(2)
P粉413307845

In tailwind, there are several props that I will explore someday. You can use tailwind's Even attribute in its child's parent div like this:

{/* Content*/}
P粉509383150

You need to use any variation. simply put:

To apply this logic to odd and even children we would use :nth-child(odd) and :nth- child(even) selector, giving them different background colors:

[&>*:nth-child(odd)]:bg-blue-500
[&>*:nth-child(even)]:bg-red-500

Practice:

1
2
3
4
5

Tailwind-play


While this method works fine on div and li elements, it doesn't seem to work on table elements...

UserWongjn pointed out to me that the browser injects the <tbody> element. That's why the above method is applied to all elements when selecting odd elements. Our selector only selects one element, the <tbody> element!


To solve the <tbody> injection problem, we can change the selector to select the children of <tbody>:

[&>tbody>*:nth-child(odd)]

Practice:


name title1
name title1
name title1

Tailwind-Play

As opensas suggested, it is possible to manually insert <tbody>:

name title1
name title1
name title1
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template