Labs ICT
Pro Login

Grid Gap

When you have a grid of items, you usually want some space between them. The gap property (formerly grid-gap) adds spacing between grid tracks without adding space at the edges. It is like margin between items, but cleaner because you do not need to worry about the outer edges.

Row and Column Gaps

You can set row and column gaps independently using row-gap and column-gap, or use the gap shorthand to set both at once.


.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

/* Or set them separately */
.container {
  row-gap: 20px;
  column-gap: 30px;
}
    

When you use one value with gap, it applies to both rows and columns. Use two values to set them separately — the first is the row gap, the second is the column gap.

Try it Yourself →

Gap Also Works with Flexbox

Gap is not just for grid — it works with flexbox too. This is a relatively recent addition and it makes flex layouts much cleaner. Before gap support in flexbox, you had to use margins and deal with the extra space on the edges.


.flex-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
    

The gap property gives you consistent spacing between flex items without any of the margin hacks. It is supported in all modern browsers.

Practical Example

Here is a typical card grid with gaps. Notice how clean the spacing is — no need to calculate margins or worry about the last item having extra space.


.gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 24px;
}

.gallery-item {
  border-radius: 8px;
  overflow: hidden;
}
    

The auto-fill with minmax creates as many columns as will fit, and gap handles all the spacing automatically. This is one of the most useful patterns in modern CSS.