CSS
Adding Gaps Between Flex Items Using CSS `gap`
Discover how to efficiently add consistent spacing between flex items and rows using the modern `gap` CSS property, simplifying layouts and eliminating complex margin hacks.
.flex-container {
display: flex;
flex-wrap: wrap; /* Important for multi-row gaps */
gap: 20px; /* Applies 20px space between items and between rows */
/* Or specify separately: */
/* row-gap: 15px; */
/* column-gap: 10px; */
padding: 10px; /* Example padding */
background-color: #f0f0f0;
border: 1px solid #ccc;
}
.flex-item {
flex: 0 0 calc(33.33% - 14px); /* Example for 3 items per row with gap */
/* (20px * 2 gaps) / 3 items = 13.33px per item, so roughly 14px reduction */
min-width: 100px;
height: 80px;
background-color: #61dafb;
color: white;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.2em;
}
How it works: The `gap` property (and its longhand `row-gap`, `column-gap`) provides a clean and intuitive way to create spacing between flex items, both horizontally and vertically when `flex-wrap: wrap` is used. Unlike margins, `gap` only applies spacing *between* items, not on the outer edges, simplifying layout calculations and removing the need for negative margins or pseudo-elements.