CSS

Distribute Elements Evenly with Flexbox and Gap

Learn to space out a group of items evenly within their container using Flexbox properties like `justify-content` and the modern `gap` property for consistent spacing.

.flex-row-even {
  display: flex;
  justify-content: space-between; /* Puts space between items */
  gap: 20px; /* Adds consistent space between items */
  flex-wrap: wrap; /* Allows items to wrap to next line */
  padding: 20px;
  background-color: #e0f2f7;
  border: 1px solid #a7d9ed;
}

.flex-item-even {
  flex: 1 1 auto; /* Allows items to grow/shrink and wrap */
  min-width: 150px; /* Minimum width before wrapping */
  padding: 15px;
  background-color: #cce7f0;
  border: 1px solid #99d0e2;
  text-align: center;
}

/* Example with space-around */
.flex-row-around {
  display: flex;
  justify-content: space-around; /* Space before, between, and after items */
  gap: 15px;
  padding: 20px;
  background-color: #ffe0b2;
  border: 1px solid #ffd599;
}

.flex-item-around {
  flex: 0 1 auto; /* Items don't grow, but shrink */
  padding: 15px;
  background-color: #ffedcc;
  border: 1px solid #ffd599;
  text-align: center;
}
How it works: This snippet illustrates how Flexbox can be used to evenly distribute items within a container, demonstrating both `space-between` and `space-around`. `justify-content: space-between` places maximum space between items, pushing the first and last items to the container's edges. `justify-content: space-around` places equal space on both sides of items. The `gap` property (which also works in Grid) provides consistent spacing *between* the flex items themselves, working in conjunction with `justify-content`. `flex-wrap: wrap` allows items to move to the next line if space is insufficient.

Need help integrating this into your project?

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

Hire DigitalCodeLabs