🧩 CSS Tutorial: gap
📌 Introduction
The gap property in CSS sets the spacing between rows and columns inflexbox, grid, and multi-column layouts. Before gap was added to flexbox, developers had to rely on margins — which caused alignment issues. With gap, spacing becomes clean, predictable, and easy to manage. ✨
🎯 What Does gap Do?
- Creates space between flex items (horizontal & vertical)
- Creates space between grid rows and columns
- Eliminates the need for margins on children
- Makes layout spacing consistent and controlled
✨ Syntax
Syntax
selector {
gap: <length>;
gap: <row-gap> <column-gap>;
}Note
gap works in: flexbox, grid, multi-column layouts. It does NOT work in block/inline elements.
🧩 gap Variants
1. Single Value (both directions)
One Value
gap: 20px;2. Two Values (row-gap + column-gap)
Two Values
gap: 10px 30px; /* row-gap: 10px, column-gap: 30px */3. row-gap
Code Snippet
row-gap: 15px;4. column-gap
Code Snippet
column-gap: 25px;🔥 Using gap in Flexbox
1. Horizontal Spacing
Flexbox Gap
.flex {
display: flex;
gap: 20px;
}2. Vertical Spacing (flex-direction: column)
Column Gap
.column {
display: flex;
flex-direction: column;
gap: 12px;
}3. Using row-gap + column-gap in Flex
Code Snippet
.flex-mixed {
display: flex;
flex-wrap: wrap;
gap: 15px 30px;
}🔥 Using gap in CSS Grid
1. Grid Gap (Simple)
Grid Gap
.grid {
display: grid;
gap: 20px;
}2. Row + Column Gap
Grid Row/Column Gap
.grid {
display: grid;
row-gap: 10px;
column-gap: 20px;
}🔥 Using gap in Multi-Column Layouts
Multi-column gap
.columns {
column-count: 3;
column-gap: 40px;
}📊 gap vs margin (Important!)
| gap | margin |
|---|---|
| Only adds space *between* items | Adds space *outside* items |
| Does not break alignment | Can cause collapsing/misalignment |
| Cleaner for layout spacing | Needs special handling on first/last child |
| Works in flex/grid | Works everywhere |
🧠 Tips & Best Practices
- Use
gapfor layout spacing; avoid margin hacks - Use separate
row-gapandcolumn-gapfor complex designs - Grid + gap is perfect for symmetrical card layouts
- Use
gapwith flex-wrap for responsive grids
>>“gap simplifies spacing — no more margin juggling, no more layout struggles.” ✨
🎉 Conclusion
The gap property makes layout spacing intuitive and consistent across flexbox, grid, and column layouts. It replaces messy margin-based spacing with a cleaner, more maintainable solution. Mastering gap is essential for building modern, scalable UI layouts. 🚀