Responsive Navbar

Resize your browser to see the mobile menu in action!

Try resizing your browser window to less than 768px wide,
or use your browser's mobile device simulator (F12 > toggle device toolbar)

How It Works

A responsive navbar has three main parts:

1. The HTML structure - Logo, hamburger button, and nav links

2. CSS media queries - Different styles for mobile vs desktop

3. JavaScript - Toggle the menu open/closed on mobile

1. HTML Structure

<nav> <a href="#" class="logo">RetroBlasts</a> <button class="hamburger" onclick="toggleMenu()"> <span></span> <span></span> <span></span> </button> <div class="nav-links" id="navLinks"> <a href="#">Home</a> <a href="#">About</a> <a href="#">Services</a> <a href="#">Contact</a> </div> </nav>

2. Desktop CSS

On desktop, the hamburger is hidden and links display horizontally:

nav { display: flex; justify-content: space-between; align-items: center; } .nav-links { display: flex; gap: 30px; } .hamburger { display: none; /* Hidden on desktop */ }

3. Mobile CSS (Media Query)

On screens smaller than 768px, we show the hamburger and hide the links:

@media (max-width: 768px) { .hamburger { display: flex; /* Show hamburger */ } .nav-links { display: none; /* Hidden by default */ position: absolute; /* Position below nav */ top: 100%; left: 0; right: 0; flex-direction: column; /* Stack vertically */ } .nav-links.active { display: flex; /* Show when toggled */ } }

4. JavaScript Toggle

A simple function to add/remove the "active" class:

function toggleMenu() { document.getElementById('navLinks').classList.toggle('active'); document.querySelector('.hamburger').classList.toggle('active'); }
Tip: The hamburger animates to an X using CSS transforms on the three spans when .active is added. Check the CSS above to see how!

Key Concepts

@media (max-width: 768px) - Styles only apply when screen is 768px or smaller

position: fixed - Keeps navbar at top even when scrolling

display: flex - Arranges items in a row (or column with flex-direction)

classList.toggle() - Adds class if missing, removes if present

z-index: 1000 - Keeps navbar above other content

Challenges to Try

1. Change the breakpoint from 768px to 1024px

2. Add a background color change when scrolling

3. Add smooth slide-down animation for the mobile menu

4. Make the links close the menu when clicked