The gap property
gap is set on a container and puts equal space between its items — only between them, with no spacing at the edges.
Syntax
gap: <gap>;
gap: <row gap> <column gap>;
gap: 16px;
gap: 8px 24px;
gap: normal; - Initial value
normal- Inherited
- no
- Applies to
- flex, grid and multi-column containers
Values
| Value | What it does |
|---|---|
<length> | a fixed gap: px, rem, em |
<percentage> | a percentage of the container's size |
normal | the initial value: 0 in flex and grid, 1em in multi-column text |
<row-gap> <column-gap> | two values: the gap between rows first, then between columns |
Example
.flex {
display: flex;
gap: 16px;
margin-bottom: 16px;
}
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px 24px;
}
.flex span,
.grid span {
padding: 12px;
background: #e0f2fe;
border: 1px solid #0284c7;
} <div class="flex">
<span>flex</span>
<span>gap: 16px</span>
<span>3</span>
</div>
<div class="grid">
<span>grid</span>
<span>gap: 8px 24px</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
</div> Result
Good to know
- Unlike margin, gap adds no space before the first or after the last item — there is no need to reset margins on the outer items.
- gap is a shorthand for row-gap and column-gap. Browsers understand the older grid-gap as an alias.
- In a wrapping flex container (flex-wrap: wrap) gap also sets the space between lines.
Sources and specification
- MDN: gap — MDN Web Docs
- CSS Gaps Module Level 1 (W3C) — W3C
See also
The flex property
The CSS flex property is a shorthand for flex-grow, flex-shrink and flex-basis: what flex: 1, flex: auto and flex: none mean and how items share space.
CSS Grid
CSS Grid lays out rows and columns: display: grid, grid-template-columns, fr, repeat() and minmax(), and a responsive grid without media queries.
The justify-content property
CSS justify-content distributes space between items along the main axis in flexbox and grid: flex-start, center, space-between, space-evenly.
The margin property
The CSS margin property sets an element's outer spacing: the 1–4 value forms, margin: auto for centering, negative margins and how vertical margins collapse.
CSS Flexbox Playground
Change flex-direction, justify-content, align-items, flex-wrap and gap and see how flexbox works right away. Copy the ready CSS code in one click.
Flexbox: header menu and a row of cards
Flexbox practice exercise: put the logo and menu side by side in the header and line course cards up in an equal-height row that wraps on narrow screens.