CSS
Consistent Spacing with CSS Flexbox Gap Property
Achieve uniform spacing between flex items using the modern `gap` property, eliminating the need for complex margin workarounds and ensuring clean, responsive layouts.
.flex-container {
display: flex;
flex-wrap: wrap; /* Allows items to wrap to the next line */
gap: 20px; /* Applies 20px space between flex items (both row and column) */
padding: 20px;
background-color: #f9f9f9;
border: 1px solid #ccc;
}
.flex-item {
flex: 1 1 200px; /* flex-grow, flex-shrink, flex-basis: Items grow, shrink, and have a base width */
background-color: #d1e9f7;
border: 1px solid #a7d9ed;
padding: 15px;
text-align: center;
min-width: 150px; /* Ensure items don't get too small */
box-sizing: border-box; /* Include padding and border in the element's total width and height */
}
/* Old way (pre-gap property) for comparison, not recommended */
/* .flex-item:not(:last-child) {
margin-right: 20px;
}
.flex-item:nth-child(3n) {
margin-right: 0;
} */
How it works: The `gap` property (originally `grid-gap` and now supported by Flexbox) provides a clean and efficient way to add consistent spacing between flex items, both horizontally and vertically, which is especially useful when `flex-wrap: wrap` is used. This simplifies responsive design by eliminating the need for complex margin rules (like targeting `:not(:last-child)` or `nth-child`) that often lead to overflow or inconsistent spacing across different rows.