Build a Simple Hamburger Menu Using HTML & CSS
Add to your RSS feed19 December 20242 min readHamburger menus are an essential feature of modern web design, providing a compact and user-friendly navigation solution. In this article, we’ll create a fully functional hamburger menu using only HTML and CSS, without relying on JavaScript.
Step 1: Setting Up the HTML Structure
Start with a simple HTML structure:
html
1 <!DOCTYPE html>2 <html lang="en">3 <head>4 <meta charset="UTF-8">5 <meta name="viewport" content="width=device-width, initial-scale=1.0">6 <title>Hamburger Menu</title>7 <link rel="stylesheet" href="styles.css">8 </head>9 <body>10 <nav class="hamburger-menu">11 <input type="checkbox" id="menu-toggle" />12 <label for="menu-toggle" class="menu-icon">13 <span></span>14 <span></span>15 <span></span>16 </label>17 <ul class="menu">18 <li><a href="#">Home</a></li>19 <li><a href="#">About</a></li>20 <li><a href="#">Services</a></li>21 <li><a href="#">Contact</a></li>22 </ul>23 </nav>24 </body>25 </html>
Explanation:
- An
<input>
with type checkbox acts as the toggle for the menu. - The
<label>
with class menu-icon serves as the visual representation of the hamburger icon. - An unordered list (
<ul>
) contains the menu links.
Step 2: Styling the Menu With CSS
Create a styles.css
file and add the following:
css
1 /* General Reset */2 body {3 margin: 0;4 font-family: Arial, sans-serif;5 }67 /* Hamburger Menu Container */8 .hamburger-menu {9 position: relative;10 }1112 /* Hide the Checkbox */13 #menu-toggle {14 display: none;15 }1617 /* Hamburger Icon */18 .menu-icon {19 display: flex;20 flex-direction: column;21 cursor: pointer;22 width: 30px;23 gap: 5px;24 }2526 .menu-icon span {27 background-color: #333;28 height: 4px;29 border-radius: 2px;30 transition: transform 0.3s, background-color 0.3s;31 }3233 /* Menu Styles */34 .menu {35 list-style: none;36 padding: 0;37 margin: 0;38 display: none;39 position: absolute;40 top: 40px;41 right: 0;42 background: #fff;43 box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);44 }4546 .menu li {47 padding: 10px 20px;48 }4950 .menu li a {51 text-decoration: none;52 color: #333;53 }5455 /* Show Menu on Checkbox Checked */56 #menu-toggle:checked ~ .menu {57 display: block;58 }5960 /* Animate Hamburger Icon */61 #menu-toggle:checked + .menu-icon span:nth-child(1) {62 transform: rotate(45deg) translateY(10px);63 }6465 #menu-toggle:checked + .menu-icon span:nth-child(2) {66 background-color: transparent;67 }6869 #menu-toggle:checked + .menu-icon span:nth-child(3) {70 transform: rotate(-45deg) translateY(-10px);71 }
Explanation:
- The
#menu-toggle:checked
selector is used to toggle the menu visibility and animate the icon. - CSS transitions and transforms add smooth animations.
Conclusion
With just HTML and CSS, you’ve created a responsive hamburger menu. This lightweight solution is perfect for projects where simplicity and speed are crucial. Expand on this by adding custom styles or integrating it into larger layouts.