gap (grid-gap)
Definition
The gap property (or grid-gap for older browsers) is a shorthand property that allows you to specify the gap between rows and columns in a CSS Grid layout. The gap property is used to set the size of the gutters (the space between grid tracks), as well as the space between the grid container's edges and the first/last grid tracks.
Examples
Setting equal row and column gaps:
.grid-container {
display: grid;
gap: 20px;
}
Setting different row and column gaps:
.grid-container {
display: grid;
row-gap: 10px;
column-gap: 20px;
}
Using the grid-gap shorthand with different values for row and column gaps:
.grid-container {
display: grid;
gap: 10px 20px;
}
Values
Value | Description |
---|---|
length | Specifies the size of the gap. |
percentage | Specifies the size of the gap as a percentage of the grid container's width or height. |
initial | Sets the gap to its default value. |
inherit | Inherits the gap from its parent element. |
Best Practices
- Use gap instead of row-gap and column-gap where possible to simplify your code.
- Use consistent gap sizes throughout your grid layout to maintain visual balance and consistency.
- Use percentage values for gaps to create more flexible and responsive layouts.
- Avoid using negative gap values, as they can cause overlapping of grid items.
- Use a fallback for browsers that do not support the gap property (e.g. row-gap and column-gap).
Browser Compatibility
Chrome | Firefox | Safari | Internet Explorer | Microsoft Edge | Opera |
---|---|---|---|---|---|
Yes | Yes | Yes | 11 and newer | Yes | Yes |