Same as the last child selector in Tailwind CSS, the first child selector works exactly the same. This is also useful in many use-cases where you just want to style only the first element in a list. Here are 2 simple methods to use first-child
selector in TailwindCSS.
Method 1: Using first-child
Selector on Parent Element
You can use the first-child
selector on the parent container in the list of elements. All the classes you apply to the first-child
will only change the style of first element in the list. Using the first-child
on the parent element makes code more readable than what is suggested on Tailwind Docs. Here is a simple example with working example on tailwind playground.
1 2 3 4 5 6 7 8 9 10 11 12 |
<ul class="list-disc [&>*:first-child]:text-blue-600 [&>*:first-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> |
The above example will show the following output on the web page.
Method 2: Using first:
Pseudo Selector on Child Elements
According to tailwindcss official docs, you should use the first:
class on the child elements when you have more than one element. This is not a what everyone is expecting in TailwindCSS. Here is an example of using the first
class in TailwindCSS.
1 2 3 4 5 6 7 8 9 10 11 12 |
<ul class="list-disc"> <li class="first:text-blue-600 first:font-bold">First List Item</li> <li class="first:text-blue-600 first:font-bold">Second List Item</li> <li class="first:text-blue-600 first:font-bold">Third List Item</li> <li class="first:text-blue-600 first:font-bold">Fourth List Item</li> <li class="first:text-blue-600 first:font-bold">Fifth List Item</li> <li class="first:text-blue-600 first:font-bold">Last List Item</li> </ul> |
Conclusion
There are 2 different methods to select the first child in TailwindCSS. The first method is to use the first-child
selector on parent container of a list and the 2nd is to use first
class on each element in the list. Both of these methods works fine and can apply styles to only the first element in a list of elements.