I’ve been trying to follow a few tutorials to turn a horizontal menubar into a drop-down hamburger menu when displayed on smaller screens, but I’m struggling to make it come together properly. I noticed a lot of tutorials seem to do away with ul/li format, which I’d like to save for semantic and accessible reasons, but this has left me struggling to get the dropdown to appear correctly on the screen.
My goal is to allow the hamburger menu to open the four menu items, centered on the screen, below the top header bar. I’ve managed to make the hamburger menu "work," but it’s opening the items not centered and not below the top menubar. Any suggestions that don’t require revamping the entire menubar code, if possible?
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>
Accompanying JSFiddle.
2
Answers
I found a fitting and elegant solution based on 54ka's answer. Instead of adding a mobile class with extra JS code, I modified screen-size restricted nav class to be the following:
This ensured that the menu would appear centered, underneath the menubar. Additional background-color and border commands can be added to clean up the dropdown menu.
You can add a window load and resizing listener. When the window gets smaller than 800px the script will add a class to your element.
I currently have it set to place a class
.mobile
. Made the necessary stylistic changes to this class for the mobile menuAdd this in your JS code:
Add this in your CSS:
EXAMPLE: