How to Use :nth-child Selector in TailwindCSS

The :nth-child selector is very helpful in CSS because it lets you select a specific element to style. You can also use the :nth-child selector to select the first child and last child. Here is a guide to using the :nth-child child selector in Tailwind CSS.

Using :nth-child on Parent Element in Tailwind CSS

You can use the :nth-child selector on the parent element when using Tailwind CSS. The syntax looks a little weird but there are a couple of benefits to using :nth-child selector on the parent element.

  • It increases the readability of the code
  • It can be used to apply more than one style to more than one child element.

Here is an example of using :nth-child in TailwindCSS. The same syntax can be used to select the first or the last element or any specific element.

You can see the working demo on the tailwind playground. The output will look like the screenshot below.

nth child selector in tailwindcss

Applying different styles to different child elements

You can also use the above method to apply different styles to different child elements using the :nth-child in TailwindCSS. The following example shows how to target two different children to add styles.

The above example selects the 3rd and 5th elements and applies different styles. You can check the working example which will look like the following image.

selecting more than one child with nth-child

The official documentation of TailwindCSS doesn’t exactly tell how to select a specific element.

Conclusion

There is no clear way to use :nth-child selector in TailwindCSS on official docs. The above examples use arbitrary values to select a specific child element or more than one child element.

Latest articles

Related articles