CSS grid-column-gap property


The grid-column-gap property (also known as column-gap in the latest CSS specifications) is used in CSS to define the space (or gap) between columns in a grid layout. This property helps in controlling the horizontal spacing between grid columns without affecting the overall structure of the grid.

Basic Syntax

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

Example

<!DOCTYPE html> <html> <head> <style> .container { display: grid; grid-template-columns: 1fr 1fr 1fr; /* Three equal columns */ grid-column-gap: 20px; /* 20px 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> </body> </html>

In this example, there are three equal-width columns (1fr 1fr 1fr), and the grid-column-gap property sets a 20-pixel gap between each column.

Values for grid-column-gap / column-gap

  • Length (px, em, rem, etc.): Defines the exact size of the gap.

    grid-column-gap: 20px;
  • Percentage (%): Defines the gap size as a percentage of the container's width.

    grid-column-gap: 5%;
  • Auto: The gap is automatically determined based on the grid layout (less commonly used).

    grid-column-gap: auto;

Practical Use Cases

1. Creating Space Between Columns

<!DOCTYPE html> <html> <head> <style> .container { display: grid; grid-template-columns: 1fr 2fr 1fr; grid-column-gap: 15px; /* 15px gap between columns */ } .item { background-color: lightgreen; padding: 20px; } </style> </head> <body> <div class="container"> <div class="item">Column 1</div> <div class="item">Column 2</div> <div class="item">Column 3</div> </div> </body> </html>

2. Using column-gap for Flexbox

While column-gap is more commonly associated with grids, it can also be used in Flexbox layouts:

.container { display: flex; column-gap: 10px; /* 10px gap between flex items */ }