CSS
Manage Spacing Between Flex Items with Gap Property
Efficiently add consistent spacing between Flexbox items using the `gap` property, simplifying layout and eliminating the need for complex margins on individual children.
.flex-container {
display: flex;
flex-wrap: wrap; /* Essential for multi-row flex containers */
gap: 20px; /* Applies 20px spacing between rows and columns */
padding: 20px;
background-color: #f9f9f9;
border: 2px dashed #ccc;
font-family: sans-serif;
max-width: 800px;
margin: 0 auto;
}
.flex-item {
background-color: #ffe0b2;
padding: 1.5em;
border: 1px solid #ffcc80;
flex: 1 1 150px; /* flex-grow, flex-shrink, flex-basis */
min-width: 150px; /* Ensure a minimum width for wrapping */
text-align: center;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
How it works: The `gap` property, originally for CSS Grid, is now fully supported in Flexbox and provides a concise way to set consistent spacing between flex items. Applying `gap: 20px` to the flex container automatically adds 20 pixels of space between all direct flex children, both horizontally and vertically, without the need for using problematic `margin` rules on individual items (like `margin-left` excluding the first item). `flex-wrap: wrap` is important to allow items to move to new rows, where the vertical `gap` will then apply.