htmltailwind-css

How to get a hoverable (bottom) navigation menu in TailwindCSS


I am trying to build a horizontal bottom menu navbar in TailwindCSS that shows an appropriate div item right above it.

The div item should be the same width as the navbar, and aligned with it.

I have the following minimalist code that shows the effect:

<div class="bg-red-50 w-full h-64">Some stuff above the menu div</div>
  
<div class="grid grid-cols-3 h-10 w-96 bg-red-50 mt-4 mx-auto relative">
    <div class="peer/menu1 cursor-pointer bg-yellow-50 w-32">
      Menu 1
    </div>
    <div class="peer/menu2 cursor-pointer bg-blue-200 w-32">
      Menu 2
    </div>
    <div class="peer/menu3 cursor-pointer bg-green-100 w-32">
      Menu 3
    </div>
    <div class="invisible absolute z-50 peer-hover/menu2:visible col-span-3 bottom-10 p-4 bg-gray-100 w-full">
      <p>Menu items 2</p>
      <p>Some more text</p>
    </div>
    <div class="invisible absolute z-50 peer-hover/menu3:visible col-span-3 bottom-10 p-4 bg-gray-100 w-full">
      <p>Menu items 3</p>
      <button class="px-2 py-1 rounded-lg m-2 bg-red-50">Button</button>
      <p>Some more text</p>
    </div>
</div>

Tailwind Play link for the code above: https://play.tailwindcss.com/Mi3hHFFEdw

The problem: as soon as I try to enter the div that shows up after e.g. hovering over menu 3, the div disappears...


Solution

  • You'd want to keep the <div> elements visible when they themselves are hovered, by adding the hover:visible class:

    <script src="https://cdn.tailwindcss.com/3.4.5"></script>
    
    <div class="bg-red-50 w-full h-64">Some stuff above the menu div</div>
      
    <div class="grid grid-cols-3 h-10 w-96 bg-red-50 mt-4 mx-auto relative">
        <div class="peer/menu1 cursor-pointer bg-yellow-50 w-32">
          Menu 1
        </div>
        <div class="peer/menu2 cursor-pointer bg-blue-200 w-32">
          Menu 2
        </div>
        <div class="peer/menu3 cursor-pointer bg-green-100 w-32">
          Menu 3
        </div>
        <div class="invisible absolute z-50 peer-hover/menu2:visible hover:visible col-span-3 bottom-10 p-4 bg-gray-100 w-full">
          <p>Menu items 2</p>
          <p>Some more text</p>
        </div>
        <div class="invisible absolute z-50 peer-hover/menu3:visible hover:visible col-span-3 bottom-10 p-4 bg-gray-100 w-full">
          <p>Menu items 3</p>
          <button class="px-2 py-1 rounded-lg m-2 bg-red-50">Button</button>
          <p>Some more text</p>
        </div>
    </div>