π What is gap in CSS Grid?
The gap property (formerly grid-gap) controls the spacing between rows and columns inside a grid container. It is one of the simplest yet most powerful layout tools in CSS Grid. Instead of using margins on individual items, gap creates consistent, automatic spacing throughout the layout.
π The 3 Gap Properties
| Property | Meaning |
|---|---|
| gap | Sets both row and column gaps |
| row-gap | Sets vertical spacing |
| column-gap | Sets horizontal spacing |
π§ͺ Basic Example
Simple Grid Gap
.container {
display: grid;
gap: 20px;
grid-template-columns: repeat(3, 1fr);
}This adds 20px spacing between all rows and columns.
π― Setting Row and Column Gaps Separately
Separate Gaps
.container {
display: grid;
row-gap: 10px;
column-gap: 30px;
}β’ Vertical spacing β 10px β’ Horizontal spacing β 30px
π Shorthand for Two Values
When you pass two values to gap:
gap: row column
gap: 10px 30px;
/* row-gap = 10px, column-gap = 30px */π§± Using gap in Responsive Grids
Responsive Gallery
.gallery {
display: grid;
gap: 15px;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}Perfect for image galleries, card layouts, and dashboards.

π§ gap vs margin β What's the Difference?
| gap | margin |
|---|---|
| Only affects space between grid items | Creates space outside an item |
| Never collapses | Vertical margins can collapse |
| Cleaner & automatic | Requires manual adjustment |
| No effect on container edges | Margin adds space around edges too |
Note
π¦ gap in Nested Grids
Nested Grid Example
.card {
display: grid;
gap: 12px;
grid-template-rows: auto 1fr auto;
}Ideal for cards with header, content, and footer.
π§© gap with Flexbox (Bonus Tip)
Modern browsers also support gap for flexbox layouts. Same syntax, same behavior!
Flexbox Gap
.buttons {
display: flex;
gap: 12px;
}Note
β οΈ Common Mistakes
- Using margin instead of gap for grids
- Expecting gap to add spacing outside the grid container
- Using px gaps for responsive layouts (try %, rem, or em instead)
- Setting negative gaps (not allowed)
π₯ Summary
The gap property simplifies spacing in CSS Grid by adding consistent, maintainable spacing between grid items. Whether you're building galleries, cards, dashboards, or product listings,gap keeps your layout clean and visually balanced.
Learn more onMDN Docs π