In this tutorial, we will be creating a responsive hamburger menu using HTML, CSS, and JavaScript. A hamburger menu is a popular navigation design pattern that consists of a menu icon that, when clicked, opens up a navigation menu. This is a great way to save space on smaller screens and provide a clean and organized navigation experience for users.
Let’s get started!
Step 1: Setting up the HTML structure
First, let’s create the basic HTML structure for our hamburger menu. We will have a nav element with a button for the menu icon and a ul element for the navigation links.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hamburger Menu</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<nav class="navbar">
<button class="menu-btn">
<span class="menu-btn__burger"></span>
</button>
<ul class="menu">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<script src="script.js"></script>
</body>
</html>
Step 2: Styling with CSS
Next, let’s style our hamburger menu using CSS. We will hide the menu by default and show it when the menu icon is clicked.
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 20px;
background-color: #333;
}
.menu-btn {
border: none;
background: none;
cursor: pointer;
}
.menu-btn__burger {
display: block;
width: 30px;
height: 3px;
background-color: #fff;
margin-bottom: 6px;
}
.menu {
display: none;
list-style: none;
padding: 0;
margin: 0;
}
.menu li {
padding: 10px;
}
.menu li a {
color: #fff;
text-decoration: none;
}
@media (max-width: 768px) {
.menu {
display: block;
background-color: #333;
position: absolute;
top: 60px;
left: 0;
width: 100%;
}
.menu li {
border-bottom: 1px solid #555;
}
}
Step 3: Adding JavaScript functionality
Lastly, we will add JavaScript to toggle the visibility of the menu when the menu icon is clicked.
const menuBtn = document.querySelector('.menu-btn');
const menu = document.querySelector('.menu');
menuBtn.addEventListener('click', () => {
menu.classList.toggle('active');
});
And that’s it! You now have a fully functional hamburger menu on your website. Play around with the CSS styles to customize the look and feel of the menu to fit your website’s design.
I hope this tutorial was helpful in creating a responsive hamburger menu using HTML, CSS, and JavaScript. Happy coding!