Even Odd Selector in TailwindCSS – [Select Even/Odd Elements]

All the selectors available in CSS are also available in Tailwind CSS. The first-child selector lets you apply styles on first-child elements and the last-child selector is useful to style the last element. However, the nth-child selector can be used to select any element from a list. You can use the nth-child selector with even and odd modifiers to select the even and odd elements. Here are 2 methods to select even and odd elements from a list.

Method 1: Using :nth-child Selector with Even and Odd Modifiers

This method is simple and useful. You can combine the even or odd modifiers with nth-child selector in TailwindCSS to style the even/odd elements. This syntax looks weird but is more helpful than what TailwindCSS recommends on their official docs. In the following example, you can see how easy it is to select even/odd elements by just adding classes to the parent element.

You can see the working example and also the output below as a screenshot.

even odd selector in tailwind css

Method 2: Using Even Odd Selector Class on Child Elements

Tailwind CSS official docs recommend using the even: and odd: modifiers on child elements in a list. If the element is even, the styles with even: modifiers will apply and if it’s an odd element the classes with :odd modifier will be applied. This is useful when you are using a framework like react, vue or laravel where you use a dynamic loop to print a list of elements. Here is an example.

In the above example, the even: modifier classes will only be applied if it’s an even element in the list and the same goes for the odd elements. You can see the working example on the tailwind playground.

Table Example with Even Odd Selector in TailwindCSS

A table would be a perfect example to demonstrate the even-odd selector in TailwindCSS. In the following code example, all the even child elements have a different background color and all the odd elements in the list have a different color for the background. There is just one place where all this is applied which is the parent element of table rows.

You can check the working example and also the screenshot of the output.

even odd selector table example in tailwind

Conclusion

The even or odd elements can be selected to apply styles in TailwindCSS with 2 different methods. The first method is to apply classes on the parent element for even-odd children and the second method is to add even and odd modifiers when printing a list with a loop. Both methods are used to select the even and odd elements to apply any styles.

Latest articles

Related articles