3 min read
•Question 46 of 49easyHow Does the gap Property Work?
Understanding spacing in flex and grid layouts.
What You'll Learn
- gap syntax
- Works with flex and grid
- Replaces margin hacks
Syntax
styles.cssCSS
.container {
gap: 20px; /* Both row and column */
gap: 20px 10px; /* row column */
row-gap: 20px;
column-gap: 10px;
}With Grid
styles.cssCSS
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}With Flexbox
styles.cssCSS
.flex {
display: flex;
flex-wrap: wrap;
gap: 10px;
}Why gap is Better
styles.cssCSS
/* Old way with margins */
.item {
margin: 10px;
}
.container {
margin: -10px; /* Compensate */
}
/* Better with gap */
.container {
display: flex;
gap: 20px;
}
/* No negative margins needed! */