CSS

Flexbox: Distribute Items Evenly with Last Item Aligned Right

Learn to create a Flexbox layout where multiple items are evenly distributed, while a specific last item is pushed to the far right using `margin-left: auto`.

.navbar {
  display: flex;
  justify-content: space-between; /* Distributes items evenly (initially) */
  align-items: center;
  background-color: #444;
  padding: 10px 20px;
  font-family: sans-serif;
}

.navbar-group {
  display: flex;
  align-items: center;
}

.navbar-item {
  color: white;
  padding: 8px 12px;
  text-decoration: none;
  margin-right: 10px;
  transition: background-color 0.3s ease;
}

.navbar-item:hover {
  background-color: #555;
  border-radius: 3px;
}

.navbar-cta {
  margin-left: auto; /* Pushes this item to the far right */
  background-color: #007bff;
  border-radius: 5px;
  padding: 8px 15px;
  color: white;
  text-decoration: none;
  transition: background-color 0.3s ease;
}

.navbar-cta:hover {
  background-color: #0056b3;
}
How it works: This snippet illustrates a common navigation bar pattern where items are distributed evenly, but a particular item (like a 'Login' or 'CTA' button) needs to be aligned to the far right. By applying `justify-content: space-between` to the flex container, items are initially spread out. Then, applying `margin-left: auto` to the specific item you want to push to the right will consume all available space to its left, effectively aligning it and any subsequent items to the far end of the container.

Need help integrating this into your project?

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

Hire DigitalCodeLabs