The problem I am having is that if I hover below “Parent” the dropdown menu appears when it should only appear when I actually hover over “Parent”. So, basically, if I hover anywhere where the submenu would be visible. Also, “Parent” does not keep the background hover colour when moving the mouse to the submenu items.
<nav
className={`fixed top-0 left-0 right-0 p-4 transition-colors duration-300 ${
scrolled ? "bg-primary" : "bg-transparent"
} z-50`}
>
<div className="container mx-auto flex items-center justify-between">
{/* Logo on the left */}
<div className="text-white text-2xl font-bold">
<a href="#">Logo</a>
</div>
{/* Menu on the right */}
<ul className="flex space-x-4">
<li>
<a
href="#"
className="text-white hover:bg-[#88c87b] px-3 py-2 rounded-md"
>
Home
</a>
</li>
<li>
<a
href="#"
className="text-white hover:bg-[#88c87b] px-3 py-2 rounded-md"
>
About
</a>
</li>
<li>
<a
href="#"
className="text-white hover:bg-[#88c87b] px-3 py-2 rounded-md"
>
Services
</a>
</li>
<li className="relative group">
{/* Dropdown trigger */}
<a
href="#"
className="text-white hover:bg-[#88c87b] px-3 py-2 rounded-md"
>
Parent
</a>
{/* Dropdown menu */}
<div className="absolute mt-2 w-48 bg-white border border-gray-200 rounded-md shadow-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 z-50">
<a
href="#"
className="block px-4 py-2 text-gray-800 hover:bg-gray-100"
>
Profile
</a>
<a
href="#"
className="block px-4 py-2 text-gray-800 hover:bg-gray-100"
>
Settings
</a>
<a
href="#"
className="block px-4 py-2 text-gray-800 hover:bg-gray-100"
>
Logout
</a>
</div>
</li>
</ul>
</div>
</nav>
So the issue you’re facing is that you’re changing the opacity when you hover on the <li class="group">
element.
The dropdown is always there and it is part of the group. (You can test it by not changing the opacity on hover and clicking on an element)
So, ideally you should hidden group-hover:flex
to ensure hovering under Parent wont show the Dialog.
<nav class="fixed left-0 right-0 top-0 z-50 bg-black p-4 transition-colors duration-300">
<ul class="flex space-x-4">
<li class="group relative">
<a href="#" class="rounded-md px-3 py-2 text-white hover:bg-[#88c87b]"> Parent </a>
<div class="absolute z-50 hidden pt-2 group-hover:flex">
<div class="w-48 rounded-md border border-gray-200 bg-white opacity-0 shadow-lg transition-opacity duration-300 group-hover:opacity-100">
<a href="#" class="block px-4 py-2 text-gray-800 hover:bg-gray-100"> Profile </a>
<a href="#" class="block px-4 py-2 text-gray-800 hover:bg-gray-100"> Settings </a>
<a href="#" class="block px-4 py-2 text-gray-800 hover:bg-gray-100"> Logout </a>
</div>
</div>
</li>
</ul>
</nav>
In this case, the opacity transition will be lost. You can create a custom animation to achieve the expected behavior (Show on hover: animate opacity from 0 to 1 and set display: flex or block) (Hide on not hover: animate opacity from 1 to 0 and set display: hidden)
Cheers