CSS
Consistent Spacing Between Flex Items with `gap` Property
Learn how to use the CSS `gap` property in Flexbox to create consistent spacing between items, simplifying layouts and removing common margin issues.
.flex-container {
display: flex;
flex-wrap: wrap; /* Optional: for multi-line items */
gap: 20px; /* Applies horizontal and vertical gap */
/* Example for different row and column gaps: gap: 10px 20px; */
background-color: #f0f0f0;
padding: 15px;
border: 1px solid #ccc;
}
.flex-item {
padding: 10px;
background-color: lightblue;
border: 1px solid steelblue;
color: #333;
font-family: sans-serif;
}
How it works: The `gap` property (formerly `grid-gap`) provides a simpler and more robust way to add consistent spacing between flex items, both horizontally and vertically, without resorting to complex margin hacks or selector-based negative margins. It works similarly to `grid-gap`, applying space *between* items, not around them, simplifying responsive designs, especially when items wrap onto multiple lines. This eliminates the need for `margin-right` on all but the last item, or `margin-bottom` on all but the last row, which significantly streamlines CSS.