CSS
Distributing Space Evenly Between Flex Items
Learn to distribute space around, between, or evenly across flex items, creating balanced layouts with consistent gaps, using `justify-content` and the `gap` property.
/* HTML Structure */
<div class="flex-container-distribute">
<div class="flex-item">Item 1</div>
<div class="flex-item">Item 2</div>
<div class="flex-item">Item 3</div>
<div class="flex-item">Item 4</div>
</div>
/* CSS */
.flex-container-distribute {
display: flex;
/* Choose one of the following for justify-content: */
/* justify-content: space-between; * default-ish, spaces between items */
/* justify-content: space-around; * spaces around items (half at ends) */
justify-content: space-evenly; /* equal space between and at ends */
gap: 10px; /* Adds consistent spacing between items directly */
border: 1px solid #ccc;
padding: 10px;
width: 100%;
min-height: 100px;
background-color: #f9f9f9;
}
.flex-item {
background-color: #8e24aa;
color: white;
padding: 15px 20px;
text-align: center;
border-radius: 5px;
}
How it works: This snippet demonstrates how Flexbox's `justify-content` property is used to distribute space along the main axis of a flex container. `space-between` places space only between items, `space-around` distributes space around items (half the amount at the ends), and `space-evenly` ensures equal space between items and at both ends. Additionally, the `gap` property provides a more modern and direct way to add consistent spacing *between* flex items, without affecting the ends.