简体   繁体   中英

What is the correct way to apply classes dynamically to odd/ even rows of Table TR element using Tailwind CSS

Trying to alternate row colors in my tailwindcss styled page, the code below has no effect on my <tr>s:

<style>
    tr:nth-child(even) {
        class="bg-gray-50";
    }
    tr:nth-child(od) {
        class="bg-white";
    }
</style>

What am I missing out please?

It seems to me that you are mixing CSS styles and HTML classes. You have to go for one or the other. Assuming that .bg-gray-50 corresponds to #ccc , you could apply the styles as follows:

<style>
    tr:nth-child(even) {
        background-color: #ccc;
    }
    tr:nth-child(od) {
        background-color: #fff;
    }
</style>

You are trying to set kind of css classes into css tags.

Plus I advice you to set border-collapse: collpase; to your table, this way, you won't have the separation between your cells.

You must set css directly like below demo:

 table{ border-collapse: collapse; } tr:nth-child(even) { /*class="bg-gray-50";*/ background: gray; } tr:nth-child(od) { /* class="bg-white";*/ background: white; }
 <table> <tbody> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> </tbody> </table>

The Tailwindish way would be to use even:someclass or odd:someclass . Needs to be enabled first, see details here

As stefan.at.wpf mentioned you should extend your tailwind config like so:

// tailwind.config.js
module.exports = {
  // ...
  variants: {
    extend: {
      backgroundColor: ['even'],
    }
  },
}

Then you can use even in your classes in like so:

<tr class="even:bg-grey">

You can achieve this using @apply and then listing the tailwind classes you want applied to the element in question.

tr:nth-child(even) {
    @apply bg-blue-50;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM