CSS

Responsive Flexbox Navigation Bar that Stacks

Build a flexible and responsive navigation bar that displays horizontally on larger screens and automatically stacks its items vertically on smaller devices using CSS Flexbox and media queries.

.nav-menu {
  display: flex;
  list-style: none;
  padding: 0;
  margin: 0;
  background-color: #333;
  gap: 20px; /* Spacing between menu items */
  flex-wrap: wrap; /* Allows items to wrap if space is too tight */
}

.nav-item a {
  text-decoration: none;
  color: white;
  padding: 15px 20px;
  display: block; /* Makes the whole link area clickable */
}

.nav-item a:hover {
  background-color: #555;
}

@media (max-width: 768px) {
  .nav-menu {
    flex-direction: column;
    align-items: stretch; /* Makes items take full width */
    gap: 0; /* Remove gap when stacked */
  }
  .nav-item a {
    padding: 10px 15px;
    border-bottom: 1px solid #444;
  }
  .nav-item:last-child a {
    border-bottom: none;
  }
}
How it works: This snippet demonstrates a responsive navigation bar using Flexbox. Initially, `display: flex` arranges menu items horizontally. A media query is used to detect smaller screens (e.g., mobile). Inside the media query, `flex-direction: column` makes the items stack vertically, and `align-items: stretch` ensures they take the full available width, creating a common mobile navigation pattern.

Need help integrating this into your project?

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

Hire DigitalCodeLabs