Frontend development · Beginner · 17 min
Build spacing utilities and a stack layout in CSS
By Padding · Updated 18 Nov 2026
Modern browsers · CSS Flexible Box Layout and Custom Properties · checked in Chromium 159
You will have a layout.css with a spacing scale, a stack and a cluster primitive and a handful of spacing utilities, and a Larkfield Clinic Confirm screen built with them in which no component declares a margin.
On this page
Spacing is the part of a stylesheet that goes wrong first. A card gets margin-bottom: 20px because it sat above a button on one screen. On the next screen it sits at the end of a list, and now there is 20 pixels of space nobody asked for. Someone adds .card:last-child { margin-bottom: 0 }, and the spacing rules are spread across every component.
The fix is to decide that components own their inside (padding, border, corners) and never their outside. Space between things belongs to the parent that lays them out. Two small layout primitives cover most screens: a stack, which puts its children in a column with a fixed gap, and a cluster, which puts short items in a row and wraps them when the row runs out of room. Both use the gap property, so the space exists only between children, never before the first or after the last.
You will write the Larkfield Clinic spacing scale as CSS custom properties, build the two primitives and a few spacing utilities in layout.css, and use them to rebuild the Confirm screen of the clinic's booking app: the title "Check your booking", the "Your appointment" summary for a nurse appointment on Tuesday 9 December at 10:30, and the "Book appointment" button. At the end you prove that no element on the page has a margin.
Step 1 · Write the spacing scale as tokens
The Larkfield scale has seven steps on a 4 pixel base: 4, 8, 12, 16, 24, 32 and 48. Each step gets a name by size, from 2xs to 2xl, so nobody has to remember which number is which job. Make a folder for the demo and put the scale in tokens.css, together with the handful of Larkfield colours the screen needs:
mkdir -p ~/spacing-demo
cd ~/spacing-demo
cat > tokens.css <<'CSS'
:root {
/* Spacing scale: 4 px base, written in rem (16 px = 1rem) */
--space-2xs: 0.25rem; /* 4 px */
--space-xs: 0.5rem; /* 8 px */
--space-s: 0.75rem; /* 12 px */
--space-m: 1rem; /* 16 px */
--space-l: 1.5rem; /* 24 px */
--space-xl: 2rem; /* 32 px */
--space-2xl: 3rem; /* 48 px */
/* Larkfield colours used by the components */
--colour-text: #1b1f24;
--colour-text-muted: #5a6270;
--colour-surface: #ffffff;
--colour-canvas: #f6f7f8;
--colour-border: #7d8592;
--colour-accent: #0f5e5a;
--colour-on-accent: #ffffff;
}
CSSThe values are in rem, not pixels. One rem is the root font size, which is 16 pixels unless the reader has changed their browser's text size. Someone who sets a larger default text size gets proportionally larger gaps as well, so the spacing keeps its relation to the words it separates. The comments keep the pixel values that the design uses, so a designer and a developer can talk about "space m, 16" and mean the same thing.
Check it worked
Run cat tokens.css. You see seven --space- lines whose pixel comments read 4, 8, 12, 16, 24, 32 and 48 in that order, and seven --colour- lines. There is no --space- value that is not on the scale, such as 20 or 10.
Step 2 · Build the Confirm screen with no layout
Now write the screen. The HTML already carries the layout class names you will define in the next steps (stack, cluster, gap-l, pad-m and so on). Until layout.css defines them they do nothing, which lets you watch each primitive change the page as you add it.
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Check your booking · Larkfield Clinic</title>
<link rel="stylesheet" href="tokens.css">
<link rel="stylesheet" href="layout.css">
<link rel="stylesheet" href="components.css">
</head>
<body>
<header class="app-header cluster gap-2xs pad-inline-m">
<a class="back-link" href="#details" aria-label="Back to your details">←</a>
<h1>Check your booking</h1>
</header>
<main class="stack gap-xl pad-m">
<div class="stack gap-l">
<section class="stack gap-m" aria-labelledby="appointment-heading">
<h2 id="appointment-heading">Your appointment</h2>
<ul class="card stack gap-s pad-m" role="list">
<li class="cluster gap-xs justify-between">
<div class="stack gap-2xs"><span class="row-label">Service</span><span>Nurse appointment, 15 min</span></div>
<a class="change-link" href="#service">Change<span class="visually-hidden"> service</span></a>
</li>
<li class="cluster gap-xs justify-between">
<div class="stack gap-2xs"><span class="row-label">Date and time</span><span>Tuesday 9 December, 10:30</span></div>
<a class="change-link" href="#time">Change<span class="visually-hidden"> date and time</span></a>
</li>
<li class="cluster gap-xs justify-between">
<div class="stack gap-2xs"><span class="row-label">Where</span><span>Larkfield Clinic, 14 Mill Lane</span></div>
<a class="change-link" href="#where">Change<span class="visually-hidden"> where</span></a>
</li>
<li class="cluster gap-xs justify-between">
<div class="stack gap-2xs"><span class="row-label">Your details</span><span>Adaeze Okonkwo-Hughes, 07700 900123</span></div>
<a class="change-link" href="#details">Change<span class="visually-hidden"> your details</span></a>
</li>
</ul>
</section>
<p class="note">Nothing is booked until you press Book appointment.</p>
</div>
<button class="button" type="button">Book appointment</button>
</main>
</body>
</html>
HTML
touch layout.cssEach "Change" link has hidden extra words, so a screen reader user hears "Change service" or "Change date and time" instead of four identical "Change" links. The summary is a list with role="list", for a reason you will see in the next step.
Then the component styles. Read them for what is missing: there is no margin anywhere. Each component sets its own size, colour, border, corners and inner padding, and nothing about the space around it.
cat > components.css <<'CSS'
body {
font-family: system-ui, sans-serif;
font-size: 1rem;
line-height: 1.5;
color: var(--colour-text);
background: var(--colour-canvas);
}
h1, h2 { font-size: 1.25rem; line-height: 1.3; }
.app-header { min-height: 3.5rem; background: var(--colour-surface); }
.back-link {
display: inline-flex; align-items: center; justify-content: center;
min-width: 2.75rem; min-height: 2.75rem;
color: var(--colour-text); text-decoration: none; font-size: 1.25rem;
}
.card {
background: var(--colour-surface);
border: 1px solid var(--colour-border);
border-radius: 0.5rem;
}
.row-label { font-size: 0.875rem; font-weight: 600; color: var(--colour-text-muted); }
.change-link {
display: inline-flex; align-items: center;
min-height: 2.75rem;
color: var(--colour-accent);
}
.note { font-size: 0.875rem; color: var(--colour-text-muted); }
.button {
min-height: 3rem;
padding-inline: var(--space-l);
border: 0;
border-radius: 0.5rem;
background: var(--colour-accent);
color: var(--colour-on-accent);
font: inherit;
font-weight: 600;
}
.visually-hidden {
position: absolute; width: 1px; height: 1px; overflow: hidden;
clip-path: inset(50%); white-space: nowrap;
}
CSSThe back link and the Change links are at least 44 by 44 pixels (2.75rem) so they are easy to hit with a thumb, and the button is 48 pixels tall. Those are sizes, which belong to the component.
Check it worked
Open index.html in your browser. On Linux, xdg-open index.html does it, on macOS open index.html, or drag the file into a browser window. The screen has Larkfield's colours, but the spacing is the browser's: the four summary rows have bullet points and a wide left indent, the headings have their own space above and below, the page has a thin border of space around it, and the "Book appointment" button sits a little below the note text.
Step 3 · Remove the browser's default margins
Browsers give headings, paragraphs, lists and the body default margins. Those margins are why spacing feels unpredictable: they differ by element, and vertical margins between neighbours collapse, so 16 pixels below one element and 24 above the next gives 24, not 40. Turn them all off, so that the only space on the page is space you put there on purpose:
cat > layout.css <<'CSS'
/* Base: no element brings its own outside spacing */
* { box-sizing: border-box; margin: 0; }
:where(ul[role="list"]) { list-style: none; padding: 0; }
CSSThe second rule removes bullets and indent from lists marked role="list". Safari stops announcing a list as a list once its bullets are removed, and the explicit role puts that back. The selector is wrapped in :where(), which gives it zero specificity. Without it, ul[role="list"] would outrank a single class such as .pad-m, and the card's padding would silently lose to the reset.
Check it worked
Reload. Everything is pressed together: the header text touches the edge of the window, the heading sits on the card, the rows touch each other and the button touches the note. No bullets or indent are left on the summary. This is the starting point you want: zero space everywhere, so every gap you see from now on comes from the scale.
Step 4 · Build the stack
A stack lays out its children in a column and puts the same gap between each pair. Add it to layout.css:
cat >> layout.css <<'CSS'
/* Stack: children in a column, separated by gap only */
.stack {
--gap: var(--space-m);
display: flex;
flex-direction: column;
gap: var(--gap);
}
CSSgap puts space between flex items and nowhere else, so the first child is flush with the top of the stack and the last with the bottom. A component placed in a stack does not need to know whether it is first, last or alone.
The gap is read from a custom property, --gap, with --space-m (16 pixels) as the default. The stack sets --gap on itself rather than only reading it, and that matters. Custom properties inherit: if the outer stack used a 32 pixel gap and an inner stack only read --gap, the inner one would inherit 32. Because every .stack sets its own default, a nested stack starts from 16 again unless you say otherwise.
Check it worked
Reload. The content opens up evenly: the summary section and the note are 16 pixels apart, the button is 16 pixels below the note, the "Your appointment" heading has 16 pixels below it, the rows inside the card are 16 pixels apart, and inside each row the label sits 16 pixels above its value. The header is not in a stack and the padding utilities do not exist yet, so the header still sits directly on the content and the content touches the window edges; later steps fix both. Every vertical gap inside main is the same, which is too uniform, and the step after next fixes that. To see it, open DevTools (F12), select main in the Elements panel and look at Computed: row-gap is 16px.
Step 5 · Build the cluster
A cluster is for short items that sit side by side and should wrap rather than overflow: the back link and title in the header, a label and its "Change" link, a row of tags or buttons. Add it:
cat >> layout.css <<'CSS'
/* Cluster: inline items that wrap onto new lines when they run out of room */
.cluster {
--gap: var(--space-xs);
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--gap);
}
CSSflex-wrap: wrap is the important line. When the items do not fit on one line, the last ones move to the next line, and gap spaces them in both directions: 8 pixels between items on a line and 8 pixels between lines. align-items: center lines up items of different heights, such as a 44 pixel link next to a 20 pixel label.
Check it worked
Reload. The back arrow and "Check your booking" now sit on one line in the header. In the summary, each row's label and value are on the left and its "Change" link follows on the same line, 8 pixels after the value, except where there is no room: make the window narrow and the "Your details" row runs out of space first, so its "Change" link wraps onto its own line underneath.
Step 6 · Add spacing utilities and set each gap
The primitives give every stack 16 pixels and every cluster 8. Real screens need different gaps at different levels. The Larkfield spacing rules are: inside a component is tighter than between components, groups are further apart than anything inside a group, the main action gets space-xl above it, and screen edges use space-m. A small set of utilities expresses those rules in the HTML. Add them at the end of layout.css:
cat >> layout.css <<'CSS'
/* Spacing utilities: keep these after .stack and .cluster */
.gap-2xs { --gap: var(--space-2xs); }
.gap-xs { --gap: var(--space-xs); }
.gap-s { --gap: var(--space-s); }
.gap-m { --gap: var(--space-m); }
.gap-l { --gap: var(--space-l); }
.gap-xl { --gap: var(--space-xl); }
.gap-2xl { --gap: var(--space-2xl); }
.pad-s { padding: var(--space-s); }
.pad-m { padding: var(--space-m); }
.pad-l { padding: var(--space-l); }
.pad-inline-m { padding-inline: var(--space-m); }
.justify-between { justify-content: space-between; }
CSSThe gap- utilities only change --gap, so they work on a stack and a cluster alike. They have the same specificity as .stack and .cluster, so the one later in the file wins: that is why the comment says to keep them last. The pad- utilities set padding from the scale, and there are only the ones the screen uses. Add pad-xs or pad-block-l when a screen needs it, always from the scale, never with a raw number. justify-between pushes the first and last items of a cluster to opposite ends, which puts each "Change" link at the right edge of the card on rows where it fits on the same line as the value. On a narrow screen, or with a wider font, a long row such as "Your details" wraps, and the wrapped "Change" link starts the next line at the left: that is the cluster working, not a mistake.
Now read the HTML from step 2 again, from the outside in. It is the spacing spec for the screen:
mainis a stack withgap-xlandpad-m. Its two children are the content and the button, so the button gets 32 pixels above it, and the screen edges get 16.- The content is a stack with
gap-l: the summary section and the note are separate groups, 24 pixels apart. - The section is a stack with the default
gap-m: 16 pixels from the heading to the card. - The card is a stack with
gap-sandpad-m: 12 pixels between rows, 16 inside the border. - Each row is a cluster with
gap-xs, and its label and value are a stack withgap-2xs, 4 pixels, because they belong together most tightly of all.
The gaps shrink as you go inwards. That is the "inside is tighter than between" rule, and you can check it by reading the class names without opening the browser.
Check it worked
Reload with the window about the width of a phone, or switch on your browser's device mode (Ctrl+Shift+M in Chrome DevTools, or Cmd+Shift+M on macOS) and choose a width of 390. You see a white header bar with the arrow and title, 16 pixels of space at the screen edges, 16 pixels between "Your appointment" and the card, a white card with a grey border and four rows 12 pixels apart, the note 24 pixels below the card, and a full-width dark teal "Book appointment" button 32 pixels below the note. In DevTools, hover over main with the flex overlay switched on (the flex badge in the Elements panel): the gaps are drawn as hatched bands, and the one above the button is twice as tall as the one between heading and card.
Step 7 · Prove no component has a margin
The aim was a screen with no margin declarations on components. Check the stylesheets first:
cd ~/spacing-demo
grep -n margin tokens.css layout.css components.cssThe only line printed is the reset in layout.css, * { box-sizing: border-box; margin: 0; }. Then check what the browser actually computed, which also catches margins from other sources such as the browser's own styles. With the page open, paste this into the DevTools Console:
[...document.querySelectorAll('body, body *')]
.filter((el) => {
const s = getComputedStyle(el);
return [s.marginTop, s.marginRight, s.marginBottom, s.marginLeft].some((m) => m !== '0px');
})
.map((el) => el.tagName);It returns a list of every element with a margin on any side.
Check it worked
grep prints one line, from layout.css, and nothing from components.css or tokens.css. The console snippet returns an empty array, []. If either finds something, remove the margin and give the space to the parent instead: put the element in a stack or cluster, or change that parent's gap- class.
Step 8 · Try the screen on a narrow phone and with large text
Layout primitives earn their keep when the screen is smaller or the text bigger than the design. In device mode, set the width to 320 pixels, the narrowest width WCAG's reflow rule asks pages to work at. Plenty of phones in use are close to that: many low-cost Android handsets report a width of 360 CSS pixels, and a browser's own interface can take some of that space. Then put the width back to 390 and raise the browser's text size to 200 per cent in its settings. In Chrome, the Font size menu stops at Very large (150 per cent), so go to Settings, Appearance, Customise fonts and set Font size to 32 (twice the default 16). In Firefox, go to Settings, General, Zoom, tick "Zoom text only" and set the default zoom to 200 per cent.
Two things should happen. At 320 pixels, rows whose value is too long for one line wrap: the "Change" link moves under its value instead of pushing past the card's edge. At 200 per cent text, the gaps grow with the text, because the scale is in rem: the gap above the button becomes 64 pixels instead of 32, so the spacing still looks like the same design.
The same wrapping covers translated text. If the clinic offers the app in French or Hausa, labels like "Change" or "Date and time" may be longer than in English, and a cluster wraps them instead of clipping them.
Check it worked
At 320 pixels wide there is no sideways scrolling, and the "Your details" row shows the name and number on one or two lines with "Change" underneath. At 200 per cent text the page is longer but still one column with no sideways scrolling, and the space above "Book appointment" is visibly larger than before. Nothing overlaps, and you did not write a media query.
Step 9 · Clean up
When you have finished, remove the demo folder. Copy layout.css somewhere else first if you want to keep it for a project:
cd ~
rm -rf ~/spacing-demoCheck it worked
ls ~/spacing-demo reports that there is no such file or directory.
Next steps
- The spacing scale and the rules for choosing a step come from Define a spacing scale and corner radius tokens, which explains the decisions behind each value.
- Stack and cluster are both flexbox. To go further with alignment, growing and shrinking, read Lay out components with Flexbox.
- Put the whole Larkfield token set, colours and type included, into CSS in Turn design tokens into CSS custom properties.
- For two-dimensional page layouts, where a stack is not enough, use CSS Grid.
Part of these paths
Related tutorials
- Define a spacing scale and corner radius tokensYou will have a seven-step spacing scale on a 4 px base, three corner radius tokens and two border widths in Figma variables, a reference frame with the rules for choosing a step, and a Larkfield Pick a time screen whose every gap, padding, radius and stroke is a token.
- Lay out components with FlexboxYou will build three Larkfield Clinic components with Flexbox, a header with a centred title, a service row with a trailing duration and a wrapping group of time slots, and finish with a browser test and a written rule for when to use Grid instead.
- Turn design tokens into CSS custom propertiesYou will have a two-layer tokens.css file of primitive and semantic custom properties, component styles that use only the semantic layer, a Node script that enforces that rule, and a demo page that proves one primitive change reaches every component.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials