CSS

Distributing Space Between Flex Items with justify-content

Master advanced spacing techniques in Flexbox to distribute items evenly or with specific gaps between them, enhancing component layout for navigation bars or form elements.

/* CSS */
.navbar {
  display: flex;
  justify-content: space-between; /* Distributes items with space between them */
  align-items: center; /* Vertically centers items */
  background-color: #333;
  padding: 1rem;
  list-style: none;
  margin: 0;
}

.navbar-item a {
  color: white;
  text-decoration: none;
  padding: 0.5rem 1rem;
  display: block;
}

.navbar-item:last-child {
  margin-left: auto; /* Pushes the last item to the far right */
  /* For scenarios like a logo on left, nav items in middle, login/search on right */
  /* If only `space-between` is used, it will spread all items evenly */
}

/* HTML */
<ul class="navbar">
  <li class="navbar-item"><a href="#">Home</a></li>
  <li class="navbar-item"><a href="#">About</a></li>
  <li class="navbar-item"><a href="#">Services</a></li>
  <li class="navbar-item"><a href="#">Contact</a></li>
  <li class="navbar-item"><a href="#">Login</a></li>
</ul>
How it works: This snippet showcases how `justify-content` in Flexbox can precisely control the distribution of space among items along the main axis. By setting `justify-content: space-between;`, the first item is aligned to the start, the last item to the end, and the remaining space is distributed equally between the items. Other useful values include `space-around` (even space around items, with half-sized space at ends) and `space-evenly` (all spaces, including ends, are equal). The example also includes `margin-left: auto` on the last item to demonstrate pushing a specific item to the far end, which can be useful for separating groups of navigation links.

Need help integrating this into your project?

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

Hire DigitalCodeLabs