CSS
Evenly Spaced Items with Flexbox `gap` and Distribution
Learn to effectively distribute items within a container and control spacing using Flexbox, combining `justify-content` and the modern `gap` property.
.flex-container {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to next line */
justify-content: space-between; /* Distributes items with space between them */
gap: 15px; /* Consistent spacing between items */
padding: 20px;
border: 1px solid #ccc;
background-color: #f9f9f9;
}
.flex-item {
flex: 0 0 calc(33.33% - 10px); /* For 3 items per row, accounting for gap */
min-width: 100px; /* Minimum width for items before wrapping */
height: 80px;
background-color: #28a745;
color: white;
display: flex;
justify-content: center;
align-items: center;
border-radius: 5px;
font-size: 1.1em;
}
/* Adjust flex-basis for different column counts:
- 2 items per row: flex: 0 0 calc(50% - 7.5px); (gap/2)
- 4 items per row: flex: 0 0 calc(25% - 11.25px); (gap*3/4)
Calculation for N items: calc((100% / N) - (gap * (N-1) / N)) for space-between
*/
/* Basic HTML Structure for context:
<div class="flex-container">
<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 class="flex-item">Item 5</div>
<div class="flex-item">Item 6</div>
</div>
*/
How it works: This snippet demonstrates how to achieve flexible and evenly distributed items within a container using Flexbox. `display: flex` and `flex-wrap: wrap` enable items to flow across multiple lines. `justify-content: space-between` ensures that items are pushed to the edges of the container with even space distributed between them. The modern `gap` property provides consistent spacing both horizontally and vertically between all items. The `flex-item`'s `flex-basis` is carefully calculated to accommodate the `gap` property, allowing for a precise number of items per row while maintaining responsiveness.