The grid-gap property (or simply gap in modern CSS) is a shorthand property used to define the space between rows and columns in a grid layout. It combines both the grid-row-gap and grid-column-gap properties into a single property, allowing you to control the spacing between both rows and columns simultaneously or independently.

Basic Syntax

selector { grid-gap: row-gap column-gap; } /* or using the more modern `gap` property */ selector { gap: row-gap column-gap; }

Example

<!DOCTYPE html> <html> <head> <style> .container { display: grid; grid-template-columns: 1fr 1fr 1fr; /* Three equal columns */ grid-template-rows: 100px 100px; /* Two equal rows */ grid-gap: 20px 10px; /* 20px gap between rows, 10px gap between columns */ } .item { background-color: lightcoral; padding: 20px; } </style> </head> <body> <div class="container"> <div class="item">Item 1</div> <div class="item">Item 2</div> <div class="item">Item 3</div> <div class="item">Item 4</div> <div class="item">Item 5</div> <div class="item">Item 6</div> </div> </body> </html>

In this example:

  • The grid-template-columns property creates three equal-width columns.
  • The grid-template-rows property creates two equal-height rows.
  • The grid-gap property is set to 20px 10px, which means there's a 20-pixel gap between the rows and a 10-pixel gap between the columns.

Values for grid-gap / gap

  • Single Value: If only one value is provided, it applies the same gap to both rows and columns.

    gap: 15px; /* 15px gap between both rows and columns */
  • Two Values: If two values are provided, the first value sets the gap between rows, and the second value sets the gap between columns.

    gap: 20px 10px; /* 20px gap between rows, 10px gap between columns */

Practical Use Cases

1. Uniform Gap Between Rows and Columns

<!DOCTYPE html> <html> <head> <style> .container { display: grid; grid-template-columns: 1fr 1fr 1fr; grid-gap: 10px; /* 10px gap between both rows and columns */ } .item { background-color: lightblue; padding: 20px; } </style> </head> <body> <div class="container"> <div class="item">Item 1</div> <div class="item">Item 2</div> <div class="item">Item 3</div> <div class="item">Item 4</div> <div class="item">Item 5</div> <div class="item">Item 6</div> </div> </body> </html>

2. Different Gaps Between Rows and Columns

<!DOCTYPE html> <html> <head> <style> .container { display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows: auto; grid-gap: 20px 5px; /* 20px gap between rows, 5px gap between columns */ } .item { background-color: lightgreen; padding: 20px; } </style> </head> <body> <div class="container"> <div class="item">Item 1</div> <div class="item">Item 2</div> <div class="item">Item 3</div> <div class="item">Item 4</div> <div class="item">Item 5</div> <div class="item">Item 6</div> </div> </body> </html>