CSS

Distribute Space Evenly Among Flex Items

Effectively distribute available space between or around flex items in a container, ideal for creating balanced navigation bars or content sections, using `justify-content`.

.navbar {
  display: flex;
  justify-content: space-around; /* Distributes space evenly around items */
  background-color: #4CAF50;
  padding: 10px 0;
  list-style: none; /* For nav links */
  margin: 0;
}

.navbar li a {
  color: white;
  text-decoration: none;
  padding: 8px 15px;
  display: block;
  transition: background-color 0.3s;
}

.navbar li a:hover {
  background-color: #45a049;
}

/* Example using space-between */
.footer-links {
  display: flex;
  justify-content: space-between; /* Distributes space evenly between items */
  padding: 1em;
  background-color: #eee;
  margin-top: 2em;
}

/* HTML Structure */
/*
<ul class="navbar">
  <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>

<div class="footer-links">
  <span>&copy; 2023 My Website</span>
  <span>Privacy Policy</span>
  <span>Terms of Use</span>
</div>
*/
How it works: This snippet illustrates how to distribute space evenly among flex items using the `justify-content` property. `justify-content: space-around` places equal space around each item, including half-spaces at the ends. `justify-content: space-between` places all available space uniformly between the first and last items, effectively pushing the first item to the start and the last to the end. This is perfect for creating balanced navigation bars or content rows.

Need help integrating this into your project?

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

Hire DigitalCodeLabs