Sub topic 2
Spacing Children with `gap`
Assume you know basic HTML, CSS selectors, the box model, and rem and em units. This chapter focuses on spacing between related children, especially in flex and grid layouts.
The gap property adds consistent space between flex or grid items. It belongs on the parent, so child elements need no spacing-specific margins.
.card-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr));
gap: 1.5rem;
}
.actions {
display: flex;
gap: 0.75rem;
}In a grid, gap separates both rows and columns. In a flex layout, it follows the layout direction. Use row-gap and column-gap when the two directions need different values.
When Vertical Margins Collapse
Adjacent block elements in normal flow can have collapsing vertical margins. The resulting space is the larger margin, not the sum.
.box-a { margin-bottom: 2rem; }
.box-b { margin-top: 1rem; }The space between these boxes is 2rem. This behavior does not apply to horizontal margins, and it generally does not apply between flex or grid children. Use gap when you want layout spacing that is explicit and predictable.
Spacing Stacked Siblings with a Flow Rule
For ordinary document flow, apply spacing only between consecutive siblings:
.flow > * + * {
margin-block-start: var(--flow-space, 1rem);
}
.flow.tight {
--flow-space: 0.5rem;
}This avoids a special rule for the first child and keeps the parent responsible for the rhythm. It works well for article content, while gap is usually clearer for flex and grid containers.
Line Height and Paragraph Spacing
Spacing also depends on typography. line-height controls space within a text block. Paragraph margins control space between blocks. Headings usually need less space above them than the sections they introduce need below them.
.article {
line-height: 1.5;
}
.article p {
margin-block: 0 1em;
}
.article h2 {
margin-block: 2rem 0.75rem;
}Exercise
A grid has uneven spacing because each card has a different bottom margin. What is the clearest fix?
Show answer
Remove the child margins and set one gap value on the grid container.