Grid Lines & Gaps
Grid lines are the dividing lines between tracks. They are numbered starting from 1. Gaps (gutters) add space between tracks without affecting item sizing.
1. Understanding Grid Lines
Grid lines are numbered from 1 (left/top) to n+1 (right/bottom) where n is the number of tracks. Negative numbers count from the opposite end: -1 is always the last line.
/* A 3-column grid has 4 column lines */ /* positive: 1, 2, 3, 4 */ /* negative: -4, -3, -2, -1 */ .container { grid-template-columns: 1fr 1fr 1fr; } /* col line 1 = far left */ /* col line 4 = far right */ /* col line -1 = far right (same) */
2. gap (row-gap & column-gap)
The gap property adds space between tracks. It's a shorthand for row-gap and column-gap. Gap does NOT add space at the outer edges of the grid β only between tracks.
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px; /* row and col gap = 16px */
}
/* OR: */
.container {
row-gap: 16px;
column-gap: 16px;
}3. Different Row & Column Gaps
You can specify separate values for row and column gaps using the two-value gap shorthand: gap: row-gap column-gap.
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
/* row-gap col-gap */
gap: 24px 8px;
/* 24px between rows, 8px between columns */
}4. Gap vs Padding
Gap only creates space between tracks, not at the edges. Use padding on the container to add space around the outside. Contrast gap with margin-based approaches β gap is much cleaner.
/* gap: space BETWEEN tracks only */ .container { gap: 12px; padding: 16px; /* adds outer space */ }