CSS

CSS Flexbox: Responsive Navbar with Left and Right Aligned Items

Learn to build a responsive navigation bar using CSS Flexbox, with some items aligned to the left and others to the right for a modern header layout, demonstrating `space-between` and `margin: auto`.

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

.navbar-brand {
  /* Stays on the left */
  font-weight: bold;
  font-size: 1.2em;
}

.navbar-menu {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

.navbar-menu li {
  margin-left: 20px; /* Space between menu items */
}

.navbar-menu a {
  color: white;
  text-decoration: none;
  padding: 5px 10px;
}

.navbar-actions {
  /* This group of items will be pushed to the far right */
  margin-left: auto; /* Pushes itself and subsequent items to the right */
  display: flex;
  align-items: center;
}

.navbar-actions button {
  margin-left: 10px;
  padding: 8px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
How it works: This snippet demonstrates how to create a flexible navigation bar using CSS Flexbox. The `.navbar` container uses `display: flex` and `justify-content: space-between` to distribute space between its direct children, effectively pushing the first item to the left and the last item (or groups of items) to the right. The `.navbar-actions` group leverages `margin-left: auto` to push itself and any subsequent items to the absolute far right, making it a powerful technique for aligning specific groups of navigation elements.

Need help integrating this into your project?

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

Hire DigitalCodeLabs