CSS

Responsive Navigation Bar with Flexbox

Build a flexible navigation bar that adapts to screen sizes, displaying horizontally on large screens and stacking vertically on smaller devices using Flexbox and media queries.

/* HTML Structure */
<nav class="navbar">
  <a href="#" class="brand">MySite</a>
  <ul class="nav-links">
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Services</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</nav>

/* CSS */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #444;
  padding: 10px 20px;
  color: white;
}

.brand {
  font-weight: bold;
  font-size: 1.5em;
  text-decoration: none;
  color: white;
}

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

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

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

@media (max-width: 768px) {
  .navbar {
    flex-direction: column;
    align-items: flex-start;
  }

  .nav-links {
    flex-direction: column;
    width: 100%;
  }

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

  .nav-links li a {
    padding: 12px 0;
    border-top: 1px solid #555;
  }

  .nav-links li:last-child a {
    border-bottom: 1px solid #555;
  }
}
How it works: This snippet creates a responsive navigation bar using Flexbox. The `.navbar` is a flex container with `justify-content: space-between` to separate the brand and links. The `.nav-links` list is also a flex container to lay out its items horizontally. A media query is used to transform the layout on smaller screens (`max-width: 768px`), changing the `flex-direction` of both the `.navbar` and `.nav-links` to `column`, resulting in a stacked vertical menu.

Need help integrating this into your project?

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

Hire DigitalCodeLabs