Create a Hamburger Menu with HTML & CSS
19 December 20242 min read
Hamburger 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:
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:
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:31 transform 0.3s,32 background-color 0.3s;33 }3435 /* Menu Styles */36 .menu {37 list-style: none;38 padding: 0;39 margin: 0;40 display: none;41 position: absolute;42 top: 40px;43 right: 0;44 background: #fff;45 box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);46 }4748 .menu li {49 padding: 10px 20px;50 }5152 .menu li a {53 text-decoration: none;54 color: #333;55 }5657 /* Show Menu on Checkbox Checked */58 #menu-toggle:checked ~ .menu {59 display: block;60 }6162 /* Animate Hamburger Icon */63 #menu-toggle:checked + .menu-icon span:nth-child(1) {64 transform: rotate(45deg) translateY(10px);65 }6667 #menu-toggle:checked + .menu-icon span:nth-child(2) {68 background-color: transparent;69 }7071 #menu-toggle:checked + .menu-icon span:nth-child(3) {72 transform: rotate(-45deg) translateY(-10px);73 }
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.