While technically feasible, implementing a pure CSS solution for menu functionality may be more trouble than it's worth:
.ulMenu .menu-content {
display: none;
}
.ulMenu > li:hover .menu-content {
display: inline-block;
}
.ulMenu > li .menu-content:target {
display: none;
}
<div class="nav">
<div class="drnav">
<ul class="ulMenu">
<li>
<div class="menuHeader">My Home</div>
<div class="menu-content" id="menuContent_1">
<ul>
<li><a href="#menuContent_1">item1</a></li>
<li><a href="#menuContent_1">item3</a></li>
</ul>
</div>
</li>
<li>
<div class="menuHeader">My Stuff</div>
<div class="menu-content" id="menuContent_2">
<ul>
<li><a href="#menuContent_2">item4</a></li>
<li><a href="#menuContent_2">item5</a></li>
</ul>
</div>
</li>
</ul>
</div>
</div>
In addition, once you close a menu, the only way to reopen it is by opening another one and hovering over the initial menu.
Important note:
I want to emphasize that using a :hover
-based menu in CSS may not be ideal with the increasing use of touch devices in today's web traffic. Only less than 1%
of users have JavaScript disabled, so opting for a JavaScript-based menu could provide a better user experience overall.
If you could explain your preference for a pure CSS solution, I would appreciate it. In my experience, the only practical use for pure CSS menus was on pages where JavaScript was restricted, like on payment gateways. Do you have other specific reasons for choosing CSS-only solutions?
While I am proficient in CSS, I personally prefer using JavaScript for DOM manipulations rather than trying to replicate them in CSS. Each tool has its strengths, and JavaScript is better suited for dynamic interactions. Use the right tool for the job.
Here is the input/label-based solution I mentioned earlier in the comments. By utilizing the :focus
state, I can simulate hiding/showing menu contents without JavaScript, although it still has some limitations. It's the closest alternative I can think of for achieving similar functionality purely with CSS:
.menuHeader input:focus + label,
.menuHeader label {
display: none;
}
.menuHeader:hover label
{
display: inline-block;
}
input.hidden {
position: absolute;
opacity: 0;
pointer-events: none;
}
<ul class="ulMenu">
<li>
<div class="menuHeader">
<div>My Home</div>
<input id="menuContent_1" class="hidden" type="text" />
<label class="menu-content" for="menuContent_1">
<ul>
<li><a href="#menuContent_1">item1</a></li>
<li><a href="#menuContent_1">item2</a></li>
</ul>
</label>
</div>
</li>
<li>
<div class="menuHeader">
<div>My Stuff</div>
<input id="menuContent_2" class="hidden" type="text" />
<label class="menu-content" for="menuContent_2">
<ul>
<li><a href="#menuContent_2">item4</a></li>
<li><a href="#menuContent_2">item5</a></li>
</ul>
</label>
</div>
</li>
</ul>