Recently a colleague asked how I target nested child elements on one of my sites, so I thought it was a good question and decided to write a quick demo on how to do it.
In CSS, it is pretty straightforward to target nested child elements, but with tailwind, it is not so obvious.
Say we have a list of items and we want to style the first and last item differently. For the purposes of this demo I will use rounded corners.
We want rounded corners on top of the first item, and bottom of the last item. The inner items should have no rounded corners.
Finished product
How?
We can’t simply target the children of the unordered list, because the element we need to style
is not a direct descendant of the unordered list. We need to target the child of the list item.
In this example I used an aside
element.
Full code of the list view above
<ul class="[&>li:first-child_aside]:rounded-t-lg [&>li:last-child_aside]:rounded-b-lg not-prose flex flex-col">
<li class="group relative">
<button class="block border-b py-2 pr-8 border-zinc-200 dark:border-zinc-800">
<p class="font-semibold group-hover:text-black group-hover:dark:text-white transition-colors duration-300 ease-in-out">
Item 1
</p>
</button>
<aside class="absolute -z-10 inset-0 -inset-x-3 -top-[1px] group-hover:bg-zinc-200 group-hover:dark:bg-zinc-800 transition-colors duration-300 ease-in-out"/>
</li>
<li class="group relative">
<button class="block border-b py-2 pr-8 border-zinc-200 dark:border-zinc-800">
<p class="font-semibold group-hover:text-black group-hover:dark:text-white transition-colors duration-300 ease-in-out">
Item 2
</p>
</button>
<aside class="absolute -z-10 inset-0 -inset-x-3 -top-[1px] group-hover:bg-zinc-200 group-hover:dark:bg-zinc-800 transition-colors duration-300 ease-in-out"/>
</li>
<li class="group relative">
<button class="block border-b py-2 pr-8 border-zinc-200 dark:border-zinc-800">
<p class="font-semibold group-hover:text-black group-hover:dark:text-white transition-colors duration-300 ease-in-out">
Item 3
</p>
</button>
<aside class="absolute -z-10 inset-0 -inset-x-3 -top-[1px] group-hover:bg-zinc-200 group-hover:dark:bg-zinc-800 transition-colors duration-300 ease-in-out"/>
</li>
</ul>
[&>li:first-child_aside]:rounded-t-lg
If you ever need to use a CSS property that Tailwind doesn’t include a utility for out of the box, you can also use square bracket notation to write completely arbitrary CSS.
Note the underscore in the class name. This serves as a space in Tailwind’s API.
In this case, we select the first child li
of the ul
and apply the rounded-t-lg
class to the descendant
aside
element.
Then we do the same for the last child li
and apply the rounded-b-lg
class to the descendant aside
element.
…and Voila