0
0
CSSmarkup~5 mins

Grid gap in CSS

Choose your learning style9 modes available
Introduction

Grid gap helps you add space between items in a grid layout. It makes your design look neat and easy to read.

When you want to separate boxes or cards in a grid so they don't touch each other.
When creating photo galleries with space between images.
When designing a dashboard with multiple widgets spaced evenly.
When building a product list with gaps between product cards.
When you want consistent spacing without adding margins to each item.
Syntax
CSS
grid-gap: <row-gap> <column-gap>;

/* or use the newer syntax */
gap: <row-gap> <column-gap>;

grid-gap is the older name; gap is the modern, preferred property.

You can set one value for equal row and column gaps, or two values for different spacing.

Examples
Sets equal space of 1rem between rows and columns.
CSS
gap: 1rem;
Sets 1rem space between rows and 2rem space between columns.
CSS
gap: 1rem 2rem;
Older syntax doing the same: 10px row gap and 20px column gap.
CSS
grid-gap: 10px 20px;
Sample Program

This example creates a 3-column grid with 1.5rem space between rows and 2rem space between columns. Each box is blue with white text and rounded corners. The grid container has a light gray background and some padding around it.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Grid Gap Example</title>
  <style>
    .grid-container {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 1.5rem 2rem;
      background-color: #f0f0f0;
      padding: 1rem;
    }
    .grid-item {
      background-color: #4a90e2;
      color: white;
      padding: 1rem;
      text-align: center;
      border-radius: 0.5rem;
      font-weight: bold;
      font-size: 1.2rem;
    }
  </style>
</head>
<body>
  <main>
    <section class="grid-container" aria-label="Example grid with gaps">
      <div class="grid-item">1</div>
      <div class="grid-item">2</div>
      <div class="grid-item">3</div>
      <div class="grid-item">4</div>
      <div class="grid-item">5</div>
      <div class="grid-item">6</div>
    </section>
  </main>
</body>
</html>
OutputSuccess
Important Notes

Use gap instead of grid-gap for better browser support and future-proof code.

Gap works only if the container has display: grid or display: flex.

Gap values can use any CSS length units like rem, em, px, or percentages.

Summary

Grid gap adds space between grid items easily.

Use gap with one or two values for row and column spacing.

It keeps your layout clean without extra margins on items.