← Back to all snippets
CSS

Flexbox: Responsive Navigation Bar Layout

Build a flexible and responsive navigation bar with CSS Flexbox, ensuring menu items distribute space evenly across the screen and stack vertically on smaller mobile devices.

.navbar {
  display: flex;
  justify-content: space-between; /* Distributes items and space */
  align-items: center; /* Vertically aligns items */
  padding: 1rem;
  background-color: #333;
  color: white;
}

.nav-links {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

.nav-links li {
  margin-left: 1.5rem;
}

.nav-links a {
  color: white;
  text-decoration: none;
  font-weight: bold;
}

/* Responsive behavior for smaller screens */
@media (max-width: 768px) {
  .navbar {
    flex-direction: column; /* Stacks items vertically */
    align-items: flex-start; /* Align items to the start when stacked */
  }

  .nav-links {
    flex-direction: column;
    width: 100%;
    margin-top: 1rem;
  }

  .nav-links li {
    margin: 0.5rem 0;
  }
}
How it works: This snippet creates a responsive navigation bar. The `.navbar` uses `display: flex` and `justify-content: space-between` to push content to the edges, while `align-items: center` keeps everything vertically aligned. The `.nav-links` also uses `display: flex` to arrange its items horizontally. A media query is then applied to `max-width: 768px` to switch the `flex-direction` to `column` for both the main navbar and its links, effectively stacking them vertically for mobile viewing, demonstrating a common responsive pattern.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs