I have the following simple header component with navigation items, which when hovered on should add the following two css rules to the mega-menu
div element so that it appears:
visibility: visible;
opacity: 1;
.nav-menu {
min-height: 112px;
padding-left: 5.6rem;
padding-right: 5.6rem;
background-color: green;
display: flex;
gap: 24px;
align-items: center;
justify-content: center;
}
.nav-menu li {
list-style: none;
}
.nav-menu li a {
color: white;
text-decoration: none;
}
.nav-menu li a:hover{
text-decoration: underline;
}
.mega-menu {
visibility: hidden;
opacity: 0;
position: absolute;
background-color: lightblue;
width: 100%;
min-height: 250px;
top: 128px;
text-align: center;
}
.nav-menu li a:hover .mega-menu {
visibility: visible;
opacity: 1;
}
<div class="container">
<ul class="nav-menu">
<li>
<a href="#">Navigation item</a>
</li>
<li>
<a href="#">Navigation item</a>
</li>
<li>
<a href="#">Navigation item</a>
</li>
<li>
<a href="#">Navigation item</a>
</li>
<li>
<a href="#">Navigation item</a>
</li>
</ul>
<div class="mega-menu">
This mega menu should only be visible when one of the list items in the nav
menu is hovered on (and then once open will close when no longer hovering on
the mega menu)
</div>
</div>
However, as observed through my snippet, I’m struggling to update the mega-menu
class when the a
in the nav-menu
is hovered on. Ideally the mega-menu should be visible when a list item is hovered on, or the user is hovering on the mega-menu (otherwise it should not be visible).
Any pointers as to where I’m going wrong would be really appreciated.
2
Answers
One way to do it using CSS only is by using the
has
selector on the common container, for example:The problem is that right now the
has
selector is not available on all browsers, Firefox does not implement it yet for example.This can be done without using
:has()
(which still has no support in FIrefox, unless the user explicitly enables it), and without JavaScript.First of all, the
.mega-menu
is a sibling of the UL – so we use.nav-menu:hover + .mega-menu
as our selector, to make it visible, when the UL gets hovered.But you probably don’t want it to show already when the list itself gets hovered, but only when one of the actual navigation items gets hovered?
That can be achieved here by putting
pointer-events: none
on the UL, and "reversing" that again withpointer-events: all
on the LI.