How to Select First Child in Tailwind CSS | First Child Selector

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.

The above example will show the following output on the web page.

first child selector in tailwindcss

 

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.

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.

Latest articles

Related articles