SyntaxStudy
Sign Up
html

How to Build a Responsive Navigation Menu

Create a navigation bar that collapses to a hamburger menu on mobile.

Responsive navigation is one of the most common UI patterns. Here's how to build one using HTML, CSS, and minimal JavaScript.

Approach

  1. Show full nav on desktop using display: flex.
  2. Hide nav links on mobile with display: none by default.
  3. Show a hamburger button on mobile.
  4. Toggle a .open class with JavaScript to show/hide links.

Accessibility

Add aria-expanded to the hamburger button and update it with JavaScript when toggling.

Example
<!-- HTML -->
<nav>
  <a href="/" class="logo">MyBrand</a>
  <button class="hamburger" aria-expanded="false" aria-controls="nav-links">
    <span></span><span></span><span></span>
  </button>
  <ul id="nav-links" class="nav-links">
    <li><a href="/about">About</a></li>
    <li><a href="/services">Services</a></li>
    <li><a href="/contact">Contact</a></li>
  </ul>
</nav>

<!-- CSS -->
@media (max-width: 768px) {
  .nav-links {
    display: none;
    flex-direction: column;
    width: 100%;
  }
  .nav-links.open { display: flex; }
  .hamburger { display: block; }
}

<!-- JS -->
document.querySelector('.hamburger').addEventListener('click', function() {
  const nav = document.getElementById('nav-links');
  nav.classList.toggle('open');
  this.setAttribute('aria-expanded', nav.classList.contains('open'));
});