gap
Specifies the spacing between items in a flex container or grid container at once. It is a shorthand for 'row-gap' and 'column-gap'.
Sample Code
/* Same gap for rows and columns */
.container { display: flex; flex-wrap: wrap; gap: 20px;}
/* Different gap for rows and columns (row-gap column-gap) */
.container-diff { display: flex; flex-wrap: wrap; gap: 10px 20px;}
/* Also works with Grid */
.grid { display: grid; gap: 16px;}
Available Values
| Value | Description |
|---|---|
| <length> | Specifies the gap using a length value such as px, em, or rem. |
| <percentage> | Specifies the gap as a percentage of the container size. |
| <row-gap> <column-gap> | When two values are provided, the first sets the row gap and the second sets the column gap. |
Specifications
| Item | Details |
|---|---|
| Initial value | normal (equivalent to 0 in Flexbox) |
| Applies to | Flex containers, grid containers, and multi-column containers |
| Inherited | No |
| Animation | Animatable (interpolated as length/percentage) |
Browser Compatibility
51 and earlier ×
8 ×
7 ×
6 ×
Android Browser
57 and later ○
56 and earlier ×Overview
'gap' specifies the spacing between items. It works with both Flexbox and CSS Grid. It was previously called 'grid-gap' and was exclusive to CSS Grid, but was renamed to 'gap' when it was extended to Flexbox as well.
Difference from 'margin'
You can use 'margin' to create spacing between items, but 'gap' has several advantages.
| Feature | gap | margin |
|---|---|---|
| Spacing target | Only between items | Outside all sides of each item |
| Edge spacing | None (only between items) | Also applied to the first and last items |
| On wrap | Applies appropriate spacing automatically | Edge spacing is added at wrap boundaries |
Because 'gap' only adds space between items, there is no extra spacing at the container edges. This is the key difference from using 'margin' for spacing.
Pattern 1: Card Layout
/* Arrange cards with equal spacing and allow wrapping */
.card-container {
display: flex;
flex-wrap: wrap;
gap: 24px;
}
.card {
flex: 1 1 280px;
}
Pattern 2: Different Gap for Rows and Columns
/* Wider row gap, narrower column gap */
.container {
display: flex;
flex-wrap: wrap;
gap: 32px 16px; /* row-gap: 32px, column-gap: 16px */
}
IE Fallback
IE10/IE11 does not support 'gap' for Flexbox. If you need IE support, use 'margin' as a fallback.
/* IE fallback */
.container {
display: flex;
flex-wrap: wrap;
gap: 20px; /* For modern browsers */
}
/* For IE: use margin as a substitute */
@supports not (gap: 20px) {
.container { margin: -10px;}
.container > * { margin: 10px;}
}
Related Properties
| Property | Description |
|---|---|
| row-gap | Specifies only the gap in the row direction (cross axis). Corresponds to the first value of 'gap'. |
| column-gap | Specifies only the gap in the column direction (main axis). Corresponds to the second value of 'gap'. |
If you find any errors or copyright issues, please contact us.