⊞CSS Grid Complete Guide

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.

gapcolumn-gaprow-gapgrid-column-startgrid-column-endgrid-row-startgrid-row-end

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.

Live Demo
1
2
3
4
5
6
col 1col 2col 3col 4
CSS
/* 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) */
πŸ’‘ Lines exist between every track and at the outer edges. A 3-column grid has 4 column lines; a 4-row grid has 5 row lines.

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.

Live Demo
1
2
3
4
5
6
CSS
.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.

Live Demo
1
2
3
4
5
6
CSS
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  /*    row-gap  col-gap */
  gap: 24px 8px;
  /* 24px between rows, 8px between columns */
}
πŸ’‘ gap: 24px 8px β†’ 24px between rows (vertical space), 8px between columns (horizontal space).

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.

Live Demo
gap only
1
2
3
4
gap + padding
1
2
3
4
CSS
/* gap: space BETWEEN tracks only */
.container {
  gap: 12px;
  padding: 16px; /* adds outer space */
}