The last child selector in CSS is very useful in many situations. For example, you may not want to add border
to the last element as a divider or you may want to use last-child
the selector to style the table row differently than the reset. There are 2 different ways to style the last element in TailwindCSS.
Method 1: Using last-child
Selector in TailwindCSS
You can use the last-child
selector anywhere you have more than one item and want to style the ending element in the list. The syntax is quite different than other Tailwind classes. Here is the example code which you can check online on tailwind playground.
1 2 3 4 5 6 7 8 9 10 11 12 |
<ul class="list-disc [&>*:last-child]:text-blue-600 [&>*:last-child]: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> |
Here is the output of the above code.
Method 2: Using Default last-child
Selector from TailwindCSS
TailwindCSS also provides a default :last
pseudo-class to select the last element but you have to apply it to every child element. This looks weird until you don’t use a framework and use a loop to display elements. You need to add class to all the children elements and it will only style the last element in the list. Here is an example with a working example on tailwind.
1 2 3 4 5 6 7 8 9 10 11 12 |
<ul class="list-disc"> <li class="last:text-blue-600 last:font-bold">First List Item</li> <li class="last:text-blue-600 last:font-bold">Second List Item</li> <li class="last:text-blue-600 last:font-bold">Third List Item</li> <li class="last:text-blue-600 last:font-bold">Fourth List Item</li> <li class="last:text-blue-600 last:font-bold">Fifth List Item</li> <li class="last:text-blue-600 last:font-bold">Last List Item</li> </ul> |
Conclusion
The default :last
pseudo-class doesn’t make sense because it has to be applied on every element The second method in the above article uses the provided method on official documentation on TailwindCSS. The first method is quite useful if you are not rendering children elements in a framework like React or Vue.