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.
1 2 3 4 5 6 7 8 9 10 11 12 |
<ul class="list-disc [&>*:nth-child(3)]:text-blue-600 [&>*:nth-child(3)]:font-bold "> <li>First List Item</li> <li>Second List Item</li> <li>Third List Item</li> <li>Fourth List Item</li> <li>Fifth List Item</li> <li>Last List Item</li> </ul> |
You can see the working demo on the tailwind playground. The output will look like the screenshot below.
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
<ul class="list-disc [&>*:nth-child(3)]:text-blue-600 [&>*:nth-child(5)]:font-black "> <li>First List Item</li> <li>Second List Item</li> <li>Third List Item</li> <li>Fourth List Item</li> <li>Fifth List Item</li> <li>Last List Item</li> </ul> |
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.
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.