HomeGroup in a group with TailwindCSS.

Group in a group with TailwindCSS.

Published: 11/23/2023

Some time ago, there was a common problem of having multiple nested group classes. Imagine having a main menu dropdown group, where top level elements are groups, and sub-level elements are groups as well. You might be tempted to use something like this:

<ul class="relative">
  <li class="group">
    Top level item
    <ul class="hidden group-hover:block">
      <li class="group">
        Sub level items will be here
        <ul class="hidden group-hover:block">
          <li>Sub-sub level item 1</li>
          <li>Sub-sub level item 2</li>
          <li>Sub-sub level item 3</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

While this looks correct at first glance, but you will have all the nested levels displayed on hover over the top level item. And here's a solution.

Since Tailwind 3.2 there are now group namespaces 🎉. Here's our example reworked:

<ul class="relative">
  <li class="group/toplevel">
    Top level item
    <ul class="hidden group-hover/toplevel:block">
      <li class="group/sublevel">
        Sub level items will be here
        <ul class="hidden group-hover/sublevel:block">
          <li>Sub-sub level item 1</li>
          <li>Sub-sub level item 2</li>
          <li>Sub-sub level item 3</li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

Easy-peasy!

About Code with Node.js

This is a personal blog and reference point of a Node.js developer.

I write and explain how different Node and JavaScript aspects work, as well as research popular and cool packages, and of course fail time to time.