CSS
Managing Gaps in Flexbox Layouts with `gap` and `align-content`
Efficiently add consistent spacing between flex items and across multiple lines using the modern `gap` property and `align-content` for multiline distribution.
/* Single-line Flexbox with gap */
.flex-container-single-line {
display: flex;
justify-content: space-between; /* Distributes items with space between */
align-items: center;
gap: 20px; /* Modern way to add spacing between items */
width: 100%;
padding: 10px;
border: 1px solid #000;
margin-bottom: 20px;
}
.flex-container-single-line .flex-item {
background-color: #e2e3e5;
padding: 10px 15px;
border: 1px solid #d6d8db;
}
/* Multi-line Flexbox with gap and align-content */
.flex-container-multi-line {
display: flex;
flex-wrap: wrap;
gap: 15px 10px; /* Row-gap 15px, Column-gap 10px */
justify-content: flex-start;
align-content: space-around; /* Distributes space between lines */
height: 300px; /* For demonstration of align-content */
border: 1px solid #000;
padding: 10px;
align-items: flex-start; /* Aligns items along cross axis within their line */
}
.flex-container-multi-line .flex-item {
flex: 0 0 calc(33.33% - 10px); /* Example for 3 items per row with gap */
background-color: #d1ecf1;
padding: 15px;
text-align: center;
border: 1px solid #add8e6;
}
/* HTML Structure Example:
<div class="flex-container-single-line">
<div class="flex-item">Item 1</div>
<div class="flex-item">Item 2</div>
<div class="flex-item">Item 3</div>
</div>
<div class="flex-container-multi-line">
<div class="flex-item">Item A</div>
<div class="flex-item">Item B</div>
<div class="flex-item">Item C</div>
<div class="flex-item">Item D</div>
<div class="flex-item">Item E</div>
<div class="flex-item">Item F</div>
<div class="flex-item">Item G</div>
</div>
*/
How it works: The `gap` property (formerly `grid-gap`) provides a clean and efficient way to add consistent spacing between flex items, both for rows and columns, eliminating the need for complex margin hacks. For multi-line flex containers (those with `flex-wrap: wrap`), `align-content` controls how space is distributed between lines of items along the cross axis, similar to `justify-content` for the main axis, allowing for flexible vertical alignment of entire rows.