CSS

Responsive Flexbox Navigation Menu

Implement a flexible navigation menu that wraps items onto new lines and adjusts alignment for different screen sizes using CSS Flexbox and media queries.

.nav-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between; /* Default for larger screens */
  align-items: center;
  background-color: #333;
  padding: 10px 20px;
}

.nav-logo {
  color: white;
  font-size: 24px;
  font-weight: bold;
  margin-right: auto; /* Pushes other items to the right */
}

.nav-links {
  display: flex;
  flex-wrap: wrap; /* Allow links to wrap if needed */
  list-style: none;
  padding: 0;
  margin: 0;
}

.nav-links li {
  margin-left: 20px;
}

.nav-links a {
  color: white;
  text-decoration: none;
  padding: 5px 0;
  display: block;
}

@media (max-width: 768px) {
  .nav-container {
    flex-direction: column; /* Stack items vertically */
    align-items: flex-start; /* Align items to the start */
  }

  .nav-logo {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .nav-links {
    width: 100%; /* Take full width */
    flex-direction: column; /* Stack links vertically */
  }

  .nav-links li {
    margin-left: 0;
    margin-bottom: 10px;
    width: 100%;
  }

  .nav-links a {
    padding: 10px 0;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  }
  .nav-links li:last-child a {
    border-bottom: none;
  }
}
How it works: This snippet demonstrates creating a responsive navigation menu using Flexbox. On larger screens, items are horizontally aligned with `justify-content: space-between` and `flex-wrap: wrap`. A media query transitions the layout for smaller screens, stacking elements vertically with `flex-direction: column` and aligning them to the start, ensuring readability and usability on mobile devices.

Need help integrating this into your project?

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

Hire DigitalCodeLabs