Full answer
A stack is a list of blocks, one under another, with an equal space between them. There are three common ways to make the space.
- Margin on every item, such as
margin-bottom: 16px. The last item also gets a space after it, so the container has extra space at the bottom. People often add:last-child { margin-bottom: 0 }to remove it. Margins can also collapse, which can give surprising results. - The "owl" selector:
.stack > * + * { margin-block-start: 16px; }. It adds space only between items, so there is no extra space at the start or the end. It works for any item, even when items are added later. Use:where()to give it zero specificity, so components can still change their own margin. display: flex; flex-direction: column; gap: 16pxordisplay: grid; gap: 16px. Thegapproperty exists only between items, so it gives the same result with one line and no selector tricks. Margins on flex and grid items do not collapse. This is the simplest choice today.
Which to use?
- Use
gapwhen the container can be a flex or grid container. This is common for components. - Use the owl selector for normal flow, such as article text, where you do not want to change the display type, and where paragraphs should keep collapsing margins and normal inline behaviour.
Space belongs to the container and not to the items. If the items own their margins, moving an item to another place brings its old spacing along, and the layout breaks.
Both stacks have the same height: three boxes of 20px and two gaps of 16px, which is 92px. Neither has extra space before the first box or after the last one.
Pick one method for a whole project, so spacing is predictable.
<style>
.stack-owl > *, .stack-gap > * { height: 20px; background: #cde; }
:where(.stack-owl) > * + * { margin-block-start: 16px; }
.stack-gap { display: grid; gap: 16px; }
</style>
<div class="stack-owl" id="o"><div>1</div><div>2</div><div>3</div></div>
<div class="stack-gap" id="g"><div>1</div><div>2</div><div>3</div></div>Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
- Per-item margins leave extra space at the end.
- The owl selector adds space only between siblings.
- gap on flex or grid does the same in one line.
- Flex and grid margins do not collapse.
- Space belongs to the container.
Common mistakes
- Putting margin-bottom on every item and getting extra space at the end.
- Mixing gap, owl selectors and margins in one component.
- Letting an item keep its own spacing, so it looks wrong when moved elsewhere.
Follow-ups
- Why does the owl selector use > * + *?
- Do margins collapse between flex items?
Tips
- Compare the three options and say which you prefer and why.
- Mention that space belongs to the container.