Unit 3 · CSS: the look and the layout
Flexbox gap vs margin: spacing items
gap is a property of the flex or grid container. It puts space between the children and none on the outer edges. Margin on each child adds space at the edges too.
The mix-up
What people often think
“gap is space around each item, like margin.”
What the tutor says
gap belongs to the container. It puts space between the children and none on the outer edges.
How it works
With margins you end up fighting the first and last items: an extra gap before the first card, or after the last one, and fixes like :last-child { margin: 0 }. gap needs none of that.
gap only works on a flex or grid container. inline-block can put items in a row, but gap will do nothing there; switch the parent to display: flex.
An example
.nav {
display: flex;
gap: 12px; /* between links only */
}Close cousins of this mix-up
The tutor watches for these in the same lesson.
“Margin on each card is how you space them.”
Margin also adds space on the outer edges. gap on the container puts space only between the cards.
“inline-block puts them in a row, so the job is done.”
It lines them up, but gap only works on a flex or grid container. Put display: flex and gap on .nav.
Practise it with a tutor watching
Flexbox and grid
Lay out a row of cards with flexbox and a whole page with grid.
Free with an account. The first two units need no account.