Sub topic 5
Spacing children with gap in flexbox and grid
This chapter assumes you know the CSS box model, basic flexbox (display: flex, flex-wrap, justify-content), basic grid (grid-template-columns), and rem units. It also assumes you have seen the spacing scale from the earlier chapter, repeated here so the examples run on their own.
Why gap exists
Before gap, authors spaced the children of a flex or grid container with margins on the children. That approach has a known problem. If every card gets margin-right: 1rem, the last card in each row also gets a margin, and the row no longer lines up with the container's edge. The usual fixes are :last-child { margin-right: 0 } or negative margins on the container. Both break when items wrap, because the last item in a row is no longer the last child.
The gap property solves this by moving the spacing decision from the children to the container. The container says "put this much space between my items," and the browser places it only between items, never at the outer edges.
The syntax
gap is shorthand for two longhand properties.
| Property | Controls | Example |
|---|---|---|
| `row-gap` | Space between rows (the vertical gutter in a horizontal layout) | `row-gap: 1rem` |
| `column-gap` | Space between columns (the horizontal gutter) | `column-gap: 2rem` |
| `gap` | Both at once | `gap: 1rem 2rem` |
With one value, gap: 1rem sets both. With two values, the first is the row gap and the second is the column gap. Many people expect the opposite order, so check it when a layout looks wrong.
The two names come from the grid specification, where a "row gap" is the space between row tracks. In flexbox the same names apply, but what a "row" is depends on flex-direction. In a default flex-direction: row container that wraps, column-gap separates items on the same line and row-gap separates the wrapped lines. If you switch to flex-direction: column, row-gap separates items within a column and column-gap separates wrapped columns.
Gap in grid
Grid is where gap is most useful, because grid tracks are defined on the container and the items never need spacing rules of their own. The card list from the spine shows the usual pattern.
:root {
--space-1: 0.25rem;
--space-2: 0.5rem;
--space-3: 1rem;
--space-4: 1.5rem;
--space-5: 2.5rem;
--space-6: 4rem;
}
.card {
padding: var(--space-4);
border: 1px solid #ccc;
}
.card-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr));
gap: var(--space-4);
}Two kinds of space are at work here, and they have different jobs. padding on .card creates room between a card's border and its content. gap on .card-list creates room between the cards. The padding is the same on every side, and the gap is the same between every pair of neighbors. This follows the proximity principle: content inside one card sits closer together than the cards sit to each other, so each card reads as one unit.
Because the gap is set once on the container, the grid stays correct when the number of columns changes. At a wide viewport you might get four columns and at a narrow one you get one. The gap stays var(--space-4) in both directions throughout, and no rule needs to know which card is last in its row.
The gap is counted when the browser calculates track sizes. In minmax(16rem, 1fr), the 1fr share is computed from the width left after all gaps are subtracted. You can rely on the columns plus the gaps adding up to the container width exactly.
Gap in flexbox
Flex containers accept gap in all current browsers. It is useful for toolbars, tag lists, button groups and navigation rows, where items have different widths and a grid would be awkward.
<ul class="tags">
<li>CSS</li>
<li>Layout</li>
<li>Spacing</li>
<li>Accessibility</li>
<li>Responsive design</li>
</ul>
<style>
:root {
--space-2: 0.5rem;
--space-3: 1rem;
}
.tags {
display: flex;
flex-wrap: wrap;
gap: var(--space-2) var(--space-3);
list-style: none;
margin: 0;
padding: 0;
}
.tags li {
padding: var(--space-2) var(--space-3);
background: #eef;
}
</style>Here the row gap (between wrapped lines) is smaller than the column gap (between tags on the same line). That is a deliberate choice. Tags on one line are read left to right as a sequence, and the wider horizontal gap keeps them from running together. The tighter vertical gap keeps the wrapped lines reading as one list. When the container narrows and a tag wraps, no margin cleanup is needed, and no empty margin shows at the end of any line.
What gap does not do
Knowing the limits of gap prevents most surprises.
- It adds no space at the outer edges. The gap sits only between items. If you want space between the container's border and its first item, use
paddingon the container. - It does not collapse. Adjacent vertical margins in normal flow can merge into one (the next chapter covers this). Gap values never merge. A 1.5rem gap is always 1.5rem.
- It applies only to flex, grid and multi-column containers. Setting
gapon a plain block container has no effect. For stacked block siblings, you need a flow rule or a grid wrapper. - It cannot vary between particular pairs of items. Every gap in an axis is the same size. If one item needs more separation, give that item a margin, or restructure the markup so the items sit in separate groups.
The last point matters for grouping. Gap gives you uniform spacing, and grouping needs different spacing for different relationships. The solution is nesting, as the form example in a later chapter shows. An outer container uses a large gap between groups, and each inner container uses a smaller gap between its own members.
Combining gap with margins
Margins on flex or grid items still work, and they add to the gap. If a grid has gap: 1.5rem and one item has margin-left: 1rem, the space between that item and its left neighbor is 2.5rem. Gap does not replace or override margins.
This is the cause of a common bug in a stylesheet that has been migrated from margins to gap: the old child margins were left in place, and now every gutter is double what the designer intended. When you add gap to a container, search for margin rules on its children and remove them.
Details that cause surprises
Percentages and units
A percentage gap resolves against the content box of the container in that axis. In a grid with an indefinite height, a percentage row-gap can behave as zero during sizing and then resolve afterward, which gives unstable layouts. Use rem values or custom properties from your scale for gaps, as the rest of this tutorial does.
Justify-content and gap together
The gap value is a minimum. In a flex container with justify-content: space-between, free space is distributed between items on top of the gap. If the container is wide, the visible space between items can exceed the gap. If the container is too narrow, items wrap or overflow and the gap stays at the set size. Do not expect space-between to shrink a gap.
Hidden items
An element with display: none is not a flex or grid item, so it creates no gap. Hiding the middle item of three leaves one gap, not two. An element with visibility: hidden still takes up its box, so its gaps remain. Use display: none when you want the layout to close up.
Empty grid tracks
Grid gaps are placed between tracks, not between items. If you define a three-column grid and place items in only two of them, the empty track and the gap next to it still exist. Use auto-fit instead of auto-fill in repeat() if you want empty tracks to collapse so the items stretch to use the space.
Browser support
Flex gap arrived later than grid gap: Chrome 84, Firefox 63, and Safari 14.1. If you must support older browsers, you can test with @supports (gap: 1rem), but this only helps for grid, because older engines that supported grid also understood gap there. For flexbox, a fallback means keeping a margin approach in a separate rule. Most projects today can drop that fallback.
Choosing between gap, margin and padding
The decision comes down to where the space belongs.
Prefer gap whenever the parent is already a flex or grid container. It keeps spacing in one place, it follows your spacing scale through a single custom property, and it removes the first-child and last-child special cases. Use margin for the exceptions, such as margin-left: auto to push one navigation item to the far end of a flex row.
Gap and the spacing scale
Always set gap from a token such as var(--space-4) and not a raw number. This keeps the set of spacing values small, which is what makes groupings consistent across a page. A useful habit is to choose the gap based on the relationship between the items:
- Items that are parts of the same thing (a label and its input) use a small token, such as
--space-1. - Items that are peers in the same group (fields in one form section) use a medium token, such as
--space-3. - Items that are separate groups (cards, form sections) use a larger token, such as
--space-4or--space-5.
When a gap and the content's own padding are the same size, the eye cannot tell whether a space belongs to the item or to the gutter between items. If cards have padding: var(--space-4), make the gap between them at least as large, and larger if the cards have no visible border or background.
Exercise
A flex container with display: flex; flex-wrap: wrap; gap: 1rem 2rem; holds ten buttons. The buttons wrap onto three lines. What is the space between two buttons on the same line, and what is the space between two lines? Then the designer asks you to give the last button extra separation from the others. Which property should you use, and where?
Show answer
The first value of gap is the row gap, so the space between wrapped lines is 1rem. The second value is the column gap, so the space between buttons on the same line is 2rem. For the extra separation, add a margin to that one button, for example margin-left: 2rem on the last button. This adds to the 2rem column gap. Gap cannot vary between particular pairs of items. If the extra space should only apply when the button is first on its line, restructure the markup so the last button sits in its own container.
Exercise
A grid has gap: 1.5rem, and each card also has margin: 0 0 1.5rem 0 left over from an older design. What is the vertical space between two cards in the same column, and what is the fix?
Show answer
The space is 3rem, because the 1.5rem row gap and the 1.5rem bottom margin add together. The fix is to delete the margin rule from the cards and let the container's gap provide all the spacing between them.