- Instant help with your CSS coding problems

Select first child in TailwindCSS

Question:
How to select first child in TailwindCSS?
Answer:
/* On the parent element */
<div class="[&>*:first-child]:bg-red-200">

/* OR on children elements */
<div class="first:bg-red-200">Line-1</div>
Description:

There are two ways to get the first child in TailwindCSS. There is a solution based on the parent element and a solution based on the children elements.

The first pseudo class - children based solution

You can style an element if it’s the first child using the first modifier. This is the equivalent of the CSS pseudo class :first-child which represents the first element among a group of sibling elements. In other words, in this case, each child element must have the appropriate classes.

<div class="mt-10 w-40">
	<div class="p-2 border border-slate-400 border-t-0 first:border-t first:rounded-t-md last:rounded-b-md">Line-1</div>
	<div class="p-2 border border-slate-400 border-t-0 first:border-t first:rounded-t-md last:rounded-b-md">Line-2</div>
	<div class="p-2 border border-slate-400 border-t-0 first:border-t first:rounded-t-md last:rounded-b-md">Line-3</div>
	<div class="p-2 border border-slate-400 border-t-0 first:border-t first:rounded-t-md last:rounded-b-md">Line-4</div>
	<div class="p-2 border border-slate-400 border-t-0 first:border-t first:rounded-t-md last:rounded-b-md">Line-5</div>
	<div class="p-2 border border-slate-400 border-t-0 first:border-t first:rounded-t-md last:rounded-b-md">Line-6</div>
</div>

The result is:

Aribtrary variants - parent based solution

You can also achieve the previous result by using arbitrary variants [&>*:first-child] . In this case the parent element will get the corresponding classes. The resulting code is smaller than the previous solution.

<div class="mt-10 w-40 [&>*]:p-2 [&>*]:border [&>*]:border-slate-400 [&>*]:border-t-0 [&>*:first-child]:border-t [&>*:first-child]:rounded-t-md [&>*:last-child]:rounded-b-md">
	<div>Line-1</div>
	<div>Line-2</div>
	<div>Line-3</div>
	<div>Line-4</div>
	<div>Line-5</div>
	<div>Line-6</div>
</div>

The output result is the same.

 

Share "How to select first child in TailwindCSS?"
Interesting things
OpanAi's ChatGPT