CSS

Distribute Flex Items Evenly with `space-between` and `gap`

Learn to arrange a series of items within a container, distributing available space efficiently between them using Flexbox's `justify-content: space-between` and the `gap` property.

.container {
  display: flex;
  justify-content: space-between; /* Pushes first and last items to edges, even space between others */
  flex-wrap: wrap; /* Allow items to wrap to the next line */
  gap: 20px; /* Space between flex items (rows and columns) */
  padding: 20px;
  border: 1px solid #ccc;
  width: 100%; /* Example width */
  max-width: 800px;
  margin: 20px auto;
}

.item {
  flex: 0 0 calc(33.33% - 14px); /* For 3 items per row with 20px gap, approximate calc */
  background-color: lightcoral;
  padding: 15px;
  text-align: center;
  border-radius: 5px;
  color: white;
}

/* Alternative for more flexible sizing without manual calc */
.item-alt {
  flex: 1 1 200px; /* grow, shrink, base-width */
  background-color: lightgreen;
  padding: 15px;
  text-align: center;
  border-radius: 5px;
  color: white;
}
How it works: This snippet demonstrates how to distribute flex items evenly within a container. `display: flex` initializes the flex context. `justify-content: space-between` places the first item at the start and the last item at the end, distributing remaining space equally between the intermediate items. `flex-wrap: wrap` allows items to move to the next line if space is insufficient. The `gap` property (shorthand for `row-gap` and `column-gap`) adds consistent spacing between items, making layout calculations much simpler than traditional margins. The `flex` shorthand property on items controls their sizing and responsiveness.

Need help integrating this into your project?

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

Hire DigitalCodeLabs