← Back to all snippets
CSS

Responsive Navigation Bar with CSS Flexbox

Build a flexible and responsive navigation bar that adapts from a horizontal layout on desktop to a stacked vertical layout on mobile using CSS Flexbox.

.navbar {
  display: flex;
  justify-content: space-between; /* Space out brand and nav links */
  align-items: center;
  background-color: #333;
  padding: 10px 20px;
  color: white;
}

.nav-brand {
  font-size: 1.5em;
  font-weight: bold;
}

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

.nav-links li a {
  color: white;
  text-decoration: none;
  padding: 10px 15px;
  display: block;
  transition: background-color 0.3s ease;
}

.nav-links li a:hover {
  background-color: #575757;
  border-radius: 4px;
}

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

  .nav-brand {
    margin-bottom: 10px;
  }

  .nav-links {
    flex-direction: column; /* Stack nav items vertically */
    width: 100%; /* Make links take full width */
    margin-top: 10px;
  }

  .nav-links li {
    width: 100%;
  }

  .nav-links li a {
    padding: 10px;
    text-align: center; /* Center text in stacked links */
    border-bottom: 1px solid #444;
  }
  .nav-links li:last-child a {
    border-bottom: none;
  }
}
How it works: This snippet crafts a responsive navigation bar using CSS Flexbox. On larger screens, `display: flex` and `justify-content: space-between` align the brand and navigation links horizontally. A media query then switches `flex-direction: column` for smaller screens, causing the navigation items to stack vertically. This provides a clean, adaptable navigation experience across different device sizes using purely CSS for layout.

Need help integrating this into your project?

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

Hire DigitalCodeLabs