Home / Snippets / Layout /

Stack utility

Consistent vertical spacing with a single class — no margin overrides.

Header
Content block
Sidebar widget
Footer
Widely Supported
layoutno-js

Quick implementation

.stack {
  display: flex;
  flex-direction: column;
  gap: var(--stack-gap, 1rem);
}

/* Variant: large spacing */
.stack--lg {
  --stack-gap: 2rem;
}

/* Variant: small spacing */
.stack--sm {
  --stack-gap: 0.5rem;
}

Prompt this to your LLM

Includes role, constraints, and edge cases to handle.

You are a senior frontend engineer creating a layout utility.

Goal: A reusable .stack utility class that adds consistent vertical spacing between any child elements.

Technical constraints:
- Use display: flex with flex-direction: column and gap for spacing.
- Use a CSS custom property --stack-gap (default 1rem) so consumers can override spacing without new classes.
- Provide size variants: .stack--sm (0.5rem), .stack--lg (2rem).
- Do NOT use margin-top on children — gap handles spacing without first/last-child edge cases.

Edge cases:
- Hidden children (display: none) should not create extra gaps.
- Nested stacks should work without spacing conflicts.
- Works with any child element type — divs, sections, form fields.

Why this matters in 2026

Before gap worked in flexbox, vertical spacing meant margin-top on every child except the first — leading to endless :first-child overrides. The stack utility eliminates that entire category of bugs. One class, predictable spacing, zero margin collapsing surprises. Every design system should have this primitive.

The logic

flex-direction: column stacks children vertically. gap adds space between siblings but not before the first or after the last child — exactly what you want. The custom property --stack-gap defaults to 1rem but can be overridden inline or via modifier classes. Unlike margin, gap ignores display: none children automatically — no phantom spacing.

Accessibility & performance

The stack utility is pure layout — it doesn't affect the accessibility tree. Flexbox layout is resolved in a single pass by the browser, so there's no performance concern even with deeply nested stacks. Source order is preserved, which means screen readers and keyboard navigation follow the visual order naturally.