How to build a responsive navigation bar with Flexbox

· Category: HTML & CSS

Short answer

Use a <nav> container with display: flex, justify-content: space-between, and an unordered list. Add a media query to switch the layout to a vertical stack or toggle menu on small screens.

Steps

  1. Create a <nav> with a logo and <ul> of links.
  2. Apply display: flex and align-items: center to the nav.
  3. Use gap or margin-left: auto to distribute items.
  4. Add a hamburger button (hidden on desktop) and a media query to transform the layout.

Example

<nav class="navbar">
  <a class="logo" href="/">Brand</a>
  <ul 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>
  <button class="toggle" aria-label="open menu">&#9776;</button>
</nav>
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem 2rem;
}
.nav-links {
  display: flex;
  gap: 1.5rem;
  list-style: none;
}
@media (max-width: 600px) {
  .nav-links {
    display: none;
    flex-direction: column;
  }
  .nav-links.open {
    display: flex;
  }
}

Tips

  • Use aria-expanded on the toggle button to indicate menu state.
  • Consider position: sticky to keep the navbar visible while scrolling.
  • Test keyboard navigation to ensure the menu is fully accessible.