Home > Blockchain >  Using TailwindCSS - how to activate the "odd" variant for flex properties in an each loop
Using TailwindCSS - how to activate the "odd" variant for flex properties in an each loop

Time:03-19

I would like to be able to "flip" the order of some elements on every odd indexed element in an each loop.

The output should be:

<div />
<div />
<div />
<div />

...and so on.

So I want to do something like:

{#each elems as elem}
<div />
{/each}

Currently my tailwind.config.js includes:

variants: {
    extend: {
        flexDirection: ['odd']
    }
},

but this has no effect in the following element:

<div >

CodePudding user response:

This can be achieved doing the following:

{#each elems as elem, i}
    <div  />
{/each}

Not sure if Tailwind has a helper for that.

CodePudding user response:

Your code seems to be working as intended: Stackblitz Demo

Note that with Tailwind 3.0 and beyond, you should remove variants configuration, as they are all available for every utility by default (see here).

The <div > output is normal and expected. Tailwind will not preprocess your code into <div > on even rows and <div > on odd rows. Instead, it will create and use the following rule:

.odd\:flex-row-reverse:nth-child(odd) {
  flex-direction: row-reverse;
}

which will then override the default flex-row class for odd-numbered children.

  • Related