Tailwind-play
While this method works fine on div
and li
elements, it doesn't seem to work on table elements...
The user Wongjn pointed out to me that the browser injects a <tbody>
element. This is why the above method is applied to all the elements when selecting odd-numbered elements. Our selector chose only one element, the <tbody>
element!
Yes, the browser will often inject a
<tbody>
element between the<table>
and elements if it does not exist, so the direct descendent selectors evaluate against the<tbody>
, not the<tr>
elements
To work around the <tbody>
injection, we can change the selector to choose the child of the <tbody>
:
[&>tbody>*:nth-child(odd)]
<table class=" [&>tbody>*:nth-child(odd)]:bg-red-500 [&>tbody>*:nth-child(even)]:bg-blue-500"><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>
Tailwind-Play
As opensas suggested, it is possible to insert the <tbody>
manually:
That's great, I guess we could also explicitly add the tbody ourselves, to avoid that browser magic, like this: Tailwind-play
<table><tbody class="[&>*:nth-child(odd)]:bg-red-500 [&>*:nth-child(even)]:bg-blue-500"><tr><td>name</td><td>title1</td></tr><tr><td>name</td><td>title1</td></tr><tr><td>name</td><td>title1</td></tr></tbody></table>
in tailwind there are several props explore a little one day.. you can use the Even prop of tailwind in the parent div of its children, like this:
<div className={`even:mt-8`}><div>{/* Content*/}</div></div>
Since version 3.2 tailwind supports combining groups with arbitrary value.
<div class="group"><div class="group-[:nth-of-type(3)_&]:block"><!-- ... --></div></div>
You can put the group
className to the any parent element (in your case tr) and change styles of the any child using group-[*]:
variant.