Sub topic 7
Spacing stacked siblings with a flow rule
This chapter assumes you know the CSS box model, the difference between padding and margin, how margins collapse, and how to define a spacing scale with custom properties. Earlier chapters covered those. Here you will build one rule that spaces any vertical stack of elements, and you will learn where it breaks.
The problem: spacing a stack of unknown content
Most content on a page is a vertical stack: headings, paragraphs, lists, figures, buttons. A common first approach is to give every element a bottom margin:
p, ul, h2, figure {
margin-bottom: 1rem;
}This causes three recurring problems.
- The last child in a container gets a margin too. That creates extra space at the bottom of a card or section, and you then have to remove it with
:last-child { margin-bottom: 0; }. - Every new element type needs its own entry in the selector list.
- A component that carries its own outer margin has the margin applied to it wherever it is placed, whether or not that spacing suits the surrounding layout.
The root cause is that an element's outer margin describes the element's relationship to its neighbors, yet the element cannot know who its neighbors are. Spacing belongs to the relationship between two siblings, so the rule should be written about pairs of siblings.
The flow rule
The lobotomized owl selector, written * + *, matches any element that directly follows another element sibling. A flow rule uses it to add space only between consecutive siblings:
.flow > * + * {
margin-block-start: var(--flow-space, var(--space-3));
}
.flow.tight {
--flow-space: var(--space-2);
}Read the selector from right to left:
*is any element.+ *preceded by a sibling, so the first child is excluded..flow > ...limited to direct children of an element with the classflow.
The first child gets no top margin, and the last child gets no bottom margin because nothing sets one. The container's edges stay clean, so padding on the container is the only thing controlling space inside its border.
How the custom property works
var(--flow-space, var(--space-3)) reads the custom property --flow-space. If it is not defined, the fallback var(--space-3) is used. Custom properties inherit, so setting --flow-space on a container changes the spacing for its direct children, and also for any nested .flow that does not set its own value.
That inheritance can surprise you. A .flow.tight inside a regular .flow is fine. A regular .flow nested inside .flow.tight also inherits the tight value, because the fallback only applies when the property is entirely undefined. If you want each nested flow to reset, set the value explicitly on the nested element or use a more specific class.
Why margin-block-start
margin-block-start is the logical equivalent of margin-top in horizontal writing modes. In a vertical writing mode such as Japanese vertical text, it maps to the correct side automatically. For ordinary English pages the result is identical to margin-top, so using the logical property costs nothing and keeps the rule correct for other languages.
Using it in markup
<article class="flow">
<h2>Delivery options</h2>
<p>Orders placed before noon ship the same day.</p>
<ul>
<li>Standard: 3 to 5 days</li>
<li>Express: next day</li>
</ul>
<a href="/shipping">Full shipping policy</a>
</article>Every direct child after the heading receives the same gap. You can change the whole article's rhythm by changing one value on the container, not by editing each child.
Why one value is not enough: tightening relationships
A flow rule with a single value gives a uniform rhythm, but the proximity principle says that closer elements read as more related. A heading belongs to the paragraph below it more than to the paragraph above it. If the heading is spaced equally from both, the grouping is ambiguous.
Add exceptions for the pairs that need them:
.flow > * + * {
margin-block-start: var(--flow-space, var(--space-3));
}
.flow > * + h2,
.flow > * + h3 {
margin-block-start: var(--space-5);
}
.flow > h2 + *,
.flow > h3 + * {
margin-block-start: var(--space-2);
}Here a heading gets a large gap above it, which separates it from the previous section. The element after a heading gets a small gap, which attaches the heading to its content. The spacing ratio between the two gaps is 2.5rem to 0.5rem, so the heading clearly leans toward what follows.
The selectors have the same specificity (one class plus one or two type selectors), so the later rule wins when both match. Consider h2 directly after h3: the selector .flow > * + h2 and the selector .flow > h3 + * both match. Their specificity is equal, so source order decides. Put the "after heading" rule last, as shown, so a heading followed by a heading stays tight. Check this case on your own pages, because it is the most common place for unexpected gaps.
Interaction with margin collapsing
The flow rule uses margins, so the collapsing rules from the previous chapter still apply. Two situations matter.
First, if a child inside the flow already has its own margin-top or margin-bottom, the larger of the two adjacent margins is used and the other is discarded. If a figure has margin: 2rem 0 from a browser default or a reset, the flow rule's 1rem collapses into it and the gap is 2rem. The flow rule does not add its value to the existing margin. Reset those margins to zero for elements inside a flow.
Second, collapsing does not happen inside flex or grid containers. If you place .flow on an element with display: flex; flex-direction: column, the margins no longer collapse and they add instead. A heading with a 2.5rem margin above and a preceding paragraph with a 1rem margin below would produce 3.5rem, but with the flow rule only the top margin of the later element is set, so no addition happens. This is another benefit of the one-sided rule: because only margin-block-start is ever set, collapsing and non-collapsing contexts give the same result.
.flow > * {
margin-block: 0;
}
.flow > * + * {
margin-block-start: var(--flow-space, var(--space-3));
}The first rule zeroes inherited margins, and the second adds the one margin you want. Both have specificity of one class, so the second wins on source order.
When to use gap instead
If the container is already a flex or grid container, use gap rather than a flow rule. gap creates space between items, never at the edges, and needs no sibling selector.
.stack {
display: flex;
flex-direction: column;
gap: var(--space-3);
}The flow rule is the better choice in these cases:
- The container is a normal block container, such as an article body or a rendered Markdown document, and you do not want to change its
display. - You need per-pair exceptions, like the heading rules above.
gapis uniform for the whole container. - Content comes from a CMS and you cannot wrap or restructure it.
The table summarizes the choice.
| Situation | Better tool | Reason |
|---|---|---|
| Vertical stack of mixed content in normal flow | Flow rule | Works without changing `display` |
| Cards in a grid or items in a toolbar | `gap` | Handles both rows and columns |
| Uniform column of form fields | `gap` | Uniform spacing and no edge space |
| Prose with headings that need different gaps | Flow rule | Per-pair overrides are easy |
Hidden elements and the flow rule
The sibling selector looks at the DOM, not at what is visible. If an element has display: none, it is still the previous sibling of the next element for selector purposes, but it generates no box. Consider a hidden first child:
<div class="flow">
<p hidden>Notice</p>
<p>Visible text</p>
</div>The visible paragraph matches * + *, so it receives a top margin, even though it is visually the first item. The container then shows unwanted space at the top. Handle this either by excluding hidden elements from the selector or by toggling hidden items with a class on the container.
.flow > :not([hidden]) ~ :not([hidden]) {
margin-block-start: var(--flow-space, var(--space-3));
}This uses the general sibling combinator ~. It matches any visible element that has a visible element somewhere before it among its siblings. Its specificity is higher than the plain * + * version because of the :not() and attribute selectors, which makes overrides harder. Use it only when elements are shown and hidden dynamically.
Flow spacing in a diagram
The diagram shows which siblings receive a margin in a container with four children.
Common errors
- Applying the rule without the child combinator.
.flow * + *(no>) matches every descendant at every depth, including list items and inline elements. List items inside aulthen get margins too. Keep>unless you want that. - Putting margins on the container's own edges. Flow spacing never touches the outer edges. Use padding on the container for that, or the parent's gap.
- Forgetting that inherited custom properties pass through. A nested
.flowinherits--flow-spacefrom an ancestor, as described earlier. - Using
*and then styling an inline-block child. A margin on an inline element has no vertical effect. Elements in the stack should be block-level, or the flow container should be flex or grid withgap. - Relying on a flow rule for horizontal spacing. The rule only sets
margin-block-start. Usegapfor rows of items.
Nesting flows for grouping
Because the custom property inherits, you can express hierarchy with two levels of flow. The outer flow separates groups with a large value. The inner flow separates the items inside a group with a small one.
.page {
--flow-space: var(--space-5);
}
.page > section {
--flow-space: var(--space-3);
}Both .page and each section use the .flow class in the markup. Items inside a section are spaced by 1rem (--space-3), while sections are spaced by 2.5rem (--space-5). The gap between groups is more than double the gap inside groups, which makes each section visible without borders. This matches the ratio guidance from the forms chapter: weaker relationships get larger gaps.
Exercise
A container has class "flow" and contains a paragraph, an h2, and another paragraph. The rules are .flow > * + * { margin-block-start: 1rem; } and .flow > h2 + * { margin-block-start: 0.5rem; }. What is the gap between the h2 and the second paragraph, between the first paragraph and the h2, and above the first paragraph?
Show answer
The gap between the h2 and the second paragraph is 0.5rem, because h2 + * has higher specificity (one class, one type) than * + * (one class), so it overrides the 1rem. The gap between the first paragraph and the h2 is 1rem, from the general rule. Above the first paragraph there is no margin from the flow rule, because it has no preceding sibling.
Exercise
Why does .flow * + * (without the > child combinator) cause problems in a container that holds a list?
Show answer
Without >, the selector matches descendants at every depth, so the second and later li elements inside the list also receive the flow margin. The list items become spaced like top-level blocks, and any nested lists, inline elements and wrapper elements are affected as well. The > limits the rule to direct children.