When you design your navigation menu, make sure to give the parent container a position of relative and set the drop-down menu to position absolute. This way, you can easily position it in relation to the parent element, while keeping the burger icon in its normal place within the parent container.
In your CSS, apply the position properties I mentioned and initially set the display to none for the drop-down menu. Create an additional style for when the menu is active, with a display of block.
Now, in JavaScript, target the burger icon and add an event listener for a click that toggles the active class on the menu.
// Get the burger menu
const burgerButton = document.getElementById("burgerButton");
// Get the drop-down menu
const menu = document.getElementById("dropDownMenu");
burgerButton.addEventListener("click", function(ev){
menu.classList.toggle("active");
});
* {
padding: 0;
margin:0;
box-sizing: border-box;
}
.navbar {
border-bottom: 1px solid rgba(100, 100, 100, 1);
display: flex;
align-items: center;
padding: 0 10px;
position: relative;
}
.burger-icon {
cursor: pointer;
border-radius: 10px;
padding: 10px;
}
.burger-icon:hover {
background-color: rgba(0,0,0,0.5);
}
.logo {
margin: 0 1rem;
font-family: Arial;
}
.bar {
width: 25px;
height: 3px;
background-color: black;
border-radius: 3px;
margin: 5px 0;
}
.dropdown-menu {
position: absolute;
width: 200px;
display: none;
background-color: rgb(200,200,200);
top: 100%;
left: 0;
}
.dropdown-menu ul {
list-style: none;
display: flex;
flex-direction: column;
align-items: center;
gap: 5px;
}
.dropdown-menu ul li {
width: 100%;
padding: 10px 0;
text-align: center;
}
.dropdown-menu ul li:hover {
background-color: rgb(180,180,190);
}
a {
color: black;
text-decoration: none;
}
.active {
display: block;
}
<header class="navbar">
<!-- Burger icon -->
<div class="burger-icon" id="burgerButton">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</div>
<h2 class="logo">
Logo here
</h2>
<!-- Drop-down menu -->
<div class="dropdown-menu" id="dropDownMenu">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">etc</a></li>
</ul>
</div>
</header>