Lately, I've been experimenting with transforming a horizontal menubar into a drop-down hamburger menu for smaller screens by following various tutorials. However, I'm encountering difficulties in getting everything to work seamlessly. Many of the tutorials I've come across abandon the ul/li format, which I prefer to keep for semantic and accessibility reasons. This decision has made it challenging for me to ensure the dropdown menu appears correctly on the screen.
My objective is to have the hamburger menu open four menu items, centered on the screen below the top header bar. I've made progress in making the hamburger menu functional, but it's currently opening the items off-center and not below the top menubar. Are there any suggestions that could help me achieve this without having to completely overhaul the menubar code?
Snippet:
const menu = document.querySelector(".nav");
let open;
function openMenu() {
if (open) {
menu.style.display = "none";
open = false;
} else if (!open) {
menu.style.display = "block";
open = true;
}
}
.menubar {
width: 100%;
height: 50px;
line-height: 50px;
vertical-align: middle;
background-color: #fff;
border-bottom: 1px solid #f5f5f5;
position: fixed;
top: 0;
-webkit-user-select: all;
user-select: none;
display: flex;
align-items: center;
}
.logo {
font-size: 24px;
display: flex;
align-items: center;
padding-left: 15px;
position: absolute;
}
.nav {
display: flex;
font-size: 18px;
flex-direction: row;
list-style: none;
margin: 0 auto;
padding: 0;
}
.nav li {
margin: 0 15px;
}
.hamburger {
margin: 0 13px 0 auto;
height: inherit;
}
@media screen and (min-width: 801px) {
.nav {
display: flex !important;
}
.hamburger {
display: none;
}
}
@media screen and (max-width: 800px) {
.hamburger {
display: flex;
}
.nav {
display: none;
text-align: center;
}
}
<body>
<div class="menubar">
<a href="" class="logo">WEBSITE NAME</a>
<ul class="nav">
<li><a href="">HOME</a></li>
<li><a href="">MENU1</a></li>
<li><a href="">MENU2</a></li>
<li><a href="">ABOUT</a></li>
</ul>
<input type="image" class="hamburger" onclick={openMenu()} src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b2/Hamburger_icon.svg/800px-Hamburger_icon.svg.png" />
</div>
</body>
Check out the accompanying JSFiddle.