Usage of CSS grid-gap property

The CSS grid-gap property is used to set the spacing between grid rows and columns in a CSS Grid layout. This property provides a convenient shorthand for defining both row and column gaps simultaneously.

Syntax

selector {
    grid-gap: row-gap column-gap;
}

/* Or using single value for both */
selector {
    grid-gap: gap-value;
}

Possible Values

Value Description
length Defines the gap size in px, em, rem, etc.
percentage Defines the gap as a percentage of the container
row-gap column-gap Two values: first for rows, second for columns

Example: Grid Layout with Gap

The following example demonstrates how to create a grid layout with 20px spacing between rows and columns −

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        display: grid;
        background-color: #2ecc71;
        grid-template-columns: auto auto;
        padding: 20px;
        grid-gap: 20px 20px;
    }
    .ele {
        background-color: #ff9500;
        border: 2px solid #333;
        padding: 35px;
        font-size: 30px;
        text-align: center;
        color: white;
        font-weight: bold;
    }
</style>
</head>
<body>
    <h1>Game Board</h1>
    <div class="container">
        <div class="ele">1</div>
        <div class="ele">2</div>
        <div class="ele">3</div>
        <div class="ele">4</div>
        <div class="ele">5</div>
        <div class="ele">6</div>
    </div>
</body>
</html>
A green container with six orange numbered boxes arranged in a 2x3 grid. Each box has 20px spacing from its neighbors, creating a clean game board layout with clearly separated cells.

Example: Different Row and Column Gaps

You can specify different gap values for rows and columns −

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        display: grid;
        background-color: #3498db;
        grid-template-columns: repeat(3, 1fr);
        padding: 15px;
        grid-gap: 30px 10px; /* 30px row gap, 10px column gap */
    }
    .item {
        background-color: #e74c3c;
        padding: 20px;
        text-align: center;
        color: white;
        border-radius: 5px;
    }
</style>
</head>
<body>
    <div class="container">
        <div class="item">A</div>
        <div class="item">B</div>
        <div class="item">C</div>
        <div class="item">D</div>
        <div class="item">E</div>
        <div class="item">F</div>
    </div>
</body>
</html>
A blue container with six red boxes arranged in a 3x2 grid. The vertical spacing (row gap) is larger at 30px, while the horizontal spacing (column gap) is smaller at 10px, creating a compressed horizontal layout.

Conclusion

The grid-gap property is essential for creating well-spaced grid layouts. Use a single value for uniform spacing or two values to control row and column gaps independently for more precise layouts.

Updated on: 2026-03-15T13:12:51+05:30

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements