Frontend development · Beginner · 18 min
Lay out components with Flexbox
By Padding · Updated 18 Nov 2026
Modern browsers · CSS Flexible Box Layout Level 1 · checked in Chromium 159
You 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.
On this page
Most layout on an app screen is not page layout. It is the inside of small components: a back control and a title side by side, a label on the left and a number on the right, a row of chips that has to wrap on a narrow phone. Flexbox is the CSS layout for that job. It arranges a container's children along one line, either a row or a column, shares out the spare space on that line, and lines the items up across it.
You will build three components from the Larkfield Clinic booking app, the fictional community clinic used across the design track: the screen header from Pick a time, the service rows from Choose a service, and the Morning and Afternoon time slots for Tuesday 9 December. In the app they sit on different screens. Here they share one page so you can watch each one change as you add its rules. Each component teaches one or two Flexbox ideas, and the last steps turn what you saw into a test and a short rule for when to reach for Grid instead.
The colours and sizes come from the Larkfield high-fidelity design: accent #0F5E5A, text #1B1F24, text-muted #5A6270, line #D5D9DF, border #7D8592, surface white and canvas #F6F7F8. The design sets text in Inter. The demo uses the system font instead, which also spares a phone on prepaid data a font download.
Step 1 · Create the page
Make a demo folder with an HTML file. The markup is plain and semantic, with no layout in it, and every class you will style is already there:
mkdir -p ~/flexbox-demo
cd ~/flexbox-demo
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>Larkfield components</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="app">
<header class="app-header">
<div class="header-start">
<a class="back" href="#"><span aria-hidden="true">←</span> Back</a>
</div>
<h1>Pick a time</h1>
<div class="header-end"></div>
</header>
<main class="screen">
<section class="section" aria-labelledby="services-heading">
<h2 id="services-heading">Choose a service</h2>
<ul class="service-list" role="list">
<li><a class="service-row" href="#"><span class="service-name">GP appointment</span><span class="duration">10 min</span></a></li>
<li><a class="service-row" href="#"><span class="service-name">Nurse appointment</span><span class="duration">15 min</span></a></li>
<li><a class="service-row" href="#"><span class="service-name">Blood test</span><span class="duration">10 min</span></a></li>
<li><a class="service-row" href="#"><span class="service-name">Vaccination</span><span class="duration">15 min</span></a></li>
<li><a class="service-row" href="#"><span class="service-name">Medication review</span><span class="duration">20 min</span></a></li>
</ul>
</section>
<section class="section" aria-labelledby="day-heading">
<h2 id="day-heading">Tue 9 Dec</h2>
<h3>Morning</h3>
<ul class="slots" role="list">
<li><button type="button" class="slot">09:00</button></li>
<li><button type="button" class="slot">09:20</button></li>
<li><button type="button" class="slot">09:40</button></li>
<li><button type="button" class="slot" aria-pressed="true">10:30</button></li>
<li><button type="button" class="slot">11:00</button></li>
</ul>
<h3>Afternoon</h3>
<ul class="slots" role="list">
<li><button type="button" class="slot">14:00</button></li>
<li><button type="button" class="slot">14:40</button></li>
<li><button type="button" class="slot">15:20</button></li>
<li><button type="button" class="slot">16:00</button></li>
</ul>
</section>
</main>
</div>
</body>
</html>
HTMLA few choices in the markup matter later. The header has three children, a start slot holding the Back link, the title, and an empty end slot, because centring the title needs a matching box on each side. Each service row is one link with two spans inside, so the whole row is one tap target. The slots are plain buttons with 10:30 marked as pressed; the real Larkfield picker uses radio buttons, taken times and a tick, which build a time slot picker with radio buttons covers. Here the slots only need to be the right shape.
Now the base styles: colour variables, type sizes and borders, but no layout:
cd ~/flexbox-demo
cat > style.css <<'CSS'
:root {
--colour-text: #1b1f24;
--colour-text-muted: #5a6270;
--colour-surface: #ffffff;
--colour-canvas: #f6f7f8;
--colour-line: #d5d9df;
--colour-border: #7d8592;
--colour-accent: #0f5e5a;
--colour-on-accent: #ffffff;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: system-ui, sans-serif;
font-size: 1rem;
line-height: 1.5;
color: var(--colour-text);
background: var(--colour-canvas);
}
h1, h2, h3, p, ul { margin: 0; }
ul { padding: 0; list-style: none; }
h1, h2 { font-size: 1.25rem; line-height: 1.3; font-weight: 600; }
h3 { font-size: 0.875rem; font-weight: 600; color: var(--colour-text-muted); }
.app { max-width: 30rem; margin-inline: auto; }
.app-header {
padding: 0.25rem 0.5rem;
background: var(--colour-surface);
border-bottom: 1px solid var(--colour-line);
}
.back { color: var(--colour-accent); font-weight: 600; text-decoration: none; }
.screen { padding: 1rem; }
.service-list { background: var(--colour-surface); border-top: 1px solid var(--colour-line); }
.service-row {
padding: 0.75rem 1rem;
color: inherit;
text-decoration: none;
border-bottom: 1px solid var(--colour-line);
}
.duration { font-size: 0.875rem; line-height: 1.25rem; color: var(--colour-text-muted); }
.slot {
min-height: 2.75rem;
font: inherit;
font-weight: 600;
color: var(--colour-text);
background: var(--colour-surface);
border: 1px solid var(--colour-border);
border-radius: 0.5rem;
}
.slot[aria-pressed="true"] {
color: var(--colour-on-accent);
background: var(--colour-accent);
border-color: var(--colour-accent);
}
CSSlist-style: none removes the bullets, and role="list" on each list keeps Safari announcing it as a list once the bullets are gone.
Check it worked
Open index.html in your browser (open index.html on macOS, xdg-open index.html on Linux, or drag the file into a window). Everything is in normal flow: the Back link sits on its own line with "Pick a time" under it, the "Choose a service" heading touches the white list, each service name runs straight into its duration ("GP appointment10 min"), and the time slots stack one under another below Morning and Afternoon, each button only as wide as its time. With the bullets gone each li is still a block, so every slot gets its own line. The rest of the tutorial fixes each of these with Flexbox.
Step 2 · Stack the screen in a column
Start with the simplest flex container. display: flex turns an element into a flex container and its direct children into flex items. flex-direction picks the line they go along, the main axis. The default is row; column stacks them. gap puts space between items and nowhere else, so there is no stray margin above the first section or below the last:
cd ~/flexbox-demo
cat >> style.css <<'CSS'
/* Screen and sections: a column with fixed gaps */
.screen { display: flex; flex-direction: column; gap: 1.5rem; }
.section { display: flex; flex-direction: column; gap: 0.75rem; }
CSSIn a column, the axes swap. justify-content now works vertically, along the main axis, and align-items works horizontally, across it. The default align-items: stretch is why each section and each list still fills the full width. To see the difference, open DevTools (F12), select main, and add align-items: flex-start in the Styles pane: every section shrinks to the width of its content. Remove it again.
Check it worked
Reload. The two sections now have a clear 24-pixel gap between them, and inside each section the heading, the list and the slot groups are 12 pixels apart. The white service list still runs the full width of the screen.
Step 3 · Put the header on one row
The header needs its three children side by side and lined up through their middles. A row is the default direction, so display: flex is enough to put them on one line; align-items: center centres them across it, which matters because the 20-pixel title and the Back link are different heights:
cd ~/flexbox-demo
cat >> style.css <<'CSS'
/* Header: back control, title and an end slot on one row */
.app-header { display: flex; align-items: center; gap: 0.5rem; min-height: 3.5rem; }
.header-start, .header-end { display: flex; }
.back {
display: flex;
align-items: center;
gap: 0.25rem;
min-width: 2.75rem;
min-height: 2.75rem;
padding-inline: 0.5rem;
}
CSSThe Back link is also a flex container, with the arrow and the word as its items. That is the usual way to line an icon up with its label. It is an inline a element, but a flex item is always laid out as a block, so its min-width and min-height apply. They make it at least 44 by 44 pixels, the size the Larkfield header spec asks for so it is easy to tap.
Check it worked
Reload. Back and "Pick a time" sit on one row with their middles level. The title starts just after Back, a little left of the middle of the header. Hover over Back in DevTools: the highlighted box is at least 44 pixels tall.
Step 4 · Centre the title with flex-grow
A centred title next to a back control is a common trap. justify-content: center centres the whole group, Back included, so the title lands right of centre. text-align: center on a full-width title centres it in the space left after Back, so it lands right of centre too. What works is two boxes of equal width either side of the title. Flexbox gives you that with flex-grow:
cd ~/flexbox-demo
cat >> style.css <<'CSS'
/* Equal side slots keep the title in the true centre */
.header-start, .header-end { flex: 1 1 0; }
.app-header h1 { flex: 0 1 auto; min-width: 0; text-align: center; }
CSSflex is a shorthand for three values. The first is flex-grow, how big a share of the spare space an item takes. The second is flex-shrink, how much it gives up when there is not enough room. The third is flex-basis, the size it starts from before any growing or shrinking. Both side slots start at 0 and grow by 1, so as long as there is spare space in the header they split it equally and end up the same width whatever is inside them. The title starts at its own width (auto) and does not grow, so it sits exactly between them.
The basis is the important part. With flex: 1 1 auto the slots would start from their content, the start slot from the width of Back and the end slot from nothing, and share only what was left. They would end up different widths and the title would drift.
min-width: 0 on the title lets it shrink below the width of its longest line. A flex item normally refuses to be narrower than its content, so a long title would push Back off the edge. With it, a long title, or a translation that runs longer than the English, wraps onto two lines instead.
There is a limit. A flex item will not shrink below its content (min-width: auto), so the start slot never gets narrower than Back. When a long title uses up all the spare space, the end slot shrinks to nothing while the start slot keeps the width of Back, and the wrapped title sits a little right of centre. That is why the test at the end checks centring only with the short title.
Check it worked
Reload. "Pick a time" is centred in the header: the space from its first letter to the left edge equals the space from its last letter to the right edge. Make the window narrow and the title stays in the middle. In DevTools, double-click the title text and type a long one, such as "Choose a time for your nurse appointment": it wraps onto two lines, sits slightly right of centre, and Back stays where it was.
Step 5 · Lay out the service row
Each row has a name that may be long and a duration that must stay short and to the right. Give the name the spare space and stop the duration from ever shrinking:
cd ~/flexbox-demo
cat >> style.css <<'CSS'
/* List row: name takes the space, duration stays on the right */
.service-row { display: flex; align-items: baseline; gap: 1rem; }
.service-name { flex: 1 1 auto; min-width: 0; }
.duration { flex: none; white-space: nowrap; }
CSSThe name grows into all the spare space, which pushes the duration to the right edge of the row. justify-content: space-between would put the duration in the same place, but growing the name has one advantage: the name's box fills the row, so there is no strip of empty space between the two items, and if a row ever has no duration, the name still fills it. flex: none is short for 0 0 auto: the duration neither grows nor shrinks, and white-space: nowrap keeps "15 min" from breaking between its two words.
align-items: baseline lines the 16-pixel name and the 14-pixel duration up on the line their letters sit on, instead of on their middles. With two text sizes side by side, that is what reads as aligned.
The gap of 16 pixels keeps the two apart even when the name is long. Service names in other languages are often longer than the English, and on a 320-pixel-wide screen this is the row that breaks first.
Check it worked
Reload. Each row has the service name on the left and its duration in grey on the right, and the five durations share one right edge. The bottoms of the letters in "Nurse appointment" and "15 min" sit on the same line. In DevTools, change "Medication review" to "Medication review with the pharmacist, including repeat prescriptions" and narrow the window: the name wraps over two or three lines, and "20 min" stays on one line at the right.
Step 6 · Wrap the time slots
Flex items stay on one line by default and shrink to fit. Nine time slots squeezed onto one line become unreadable on a phone, so let them wrap:
cd ~/flexbox-demo
cat >> style.css <<'CSS'
/* Time slots: equal chips that wrap onto new rows */
.slots { display: flex; flex-wrap: wrap; gap: 0.5rem; }
.slots > li { flex: 0 0 5rem; }
.slot { width: 100%; }
CSSThe flex items are the li elements, not the buttons. Only the direct children of a flex container are flex items, so the size goes on .slots > li, and the button fills its list item. flex: 0 0 5rem makes every slot exactly 80 pixels wide: no growing, no shrinking. flex-wrap: wrap starts a new row when the next slot would not fit, and gap spaces the rows as well as the slots in a row.
On a 390-pixel-wide phone, four 80-pixel slots and their gaps fit in a row, so Morning is four slots and then 11:00 alone. At 320 pixels wide, the width WCAG 2.2 Reflow (1.4.10) expects content to work at, three fit, and nothing scrolls sideways.
Check it worked
Reload, then open your browser's responsive mode (in Chrome or Edge, the device toolbar button in DevTools) and set the width to 390. Morning shows 09:00, 09:20, 09:40 and 10:30 on the first row, with 10:30 filled in dark teal, and 11:00 alone on a second row, all the same width. Set the width to 320: three slots per row, and the page does not scroll sideways.
Step 7 · Decide between Flexbox and Grid
The lone 11:00 is a good place to see where Flexbox stops. In DevTools, select one of the Morning li elements, find the .slots > li rule and change flex: 0 0 5rem to flex: 1 0 5rem. Every slot now grows to fill its row, and 11:00, alone on its row, stretches across the full width. Flexbox shares space out one line at a time. Each row knows nothing about the row above, so items on different rows do not line up in columns. Undo the change.
If you want columns that line up across rows, that is a two-dimensional layout, and Grid is the tool. display: grid; grid-template-columns: repeat(auto-fill, minmax(5rem, 1fr)) gives slots that stretch evenly and still line up, with the last one staying the width of the others. The fixed 80-pixel Flexbox slots are a fine choice too; the point is to choose on purpose.
Write the rule down where the next person will see it, at the end of the stylesheet:
cd ~/flexbox-demo
cat >> style.css <<'CSS'
/*
Flexbox or Grid?
- Flexbox: items along one line, sized by their content or a fixed basis
(headers, list rows, toolbars, icon and label, chips that may wrap).
- Grid: items that must line up in rows and columns at the same time,
or regions placed by name (page layouts, card grids, aligned forms).
- Wrapped flex rows do not line up with each other. If they must, use Grid.
*/
CSSCheck it worked
Open style.css. It ends with the "Flexbox or Grid?" comment. Look back over the page and name the layout behind each part: the screen and sections are Flexbox columns, the header and service rows are Flexbox rows, and the slots are a wrapping Flexbox row with fixed sizes.
Step 8 · Test the layout in a browser
Looking at the page proves it works on your screen today. A short test proves it keeps working after the next change. Install Playwright in the demo folder. On Linux, --with-deps installs the system libraries Chromium needs and asks for your password:
cd ~/flexbox-demo
npm init -y > /dev/null
npm install playwright@1.65.1
npx playwright install --with-deps chromiumThen write a test that loads the page at 390 and 320 pixels wide and measures what you checked by eye:
cd ~/flexbox-demo
cat > test-layout.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
const url = new URL('./index.html', import.meta.url).href;
const rectOf = (el) => { const r = el.getBoundingClientRect(); return { x: r.x, y: r.y, w: r.width, h: r.height, right: r.right }; };
const box = (page, sel) => page.locator(sel).first().evaluate(rectOf);
const boxes = (page, sel) => page.locator(sel).evaluateAll((els) => els.map((el) => {
const r = el.getBoundingClientRect();
return { x: r.x, y: r.y, w: r.width, h: r.height, right: r.right };
}));
const browser = await chromium.launch();
for (const width of [390, 320]) {
const page = await browser.newPage({ viewport: { width, height: 844 } });
await page.goto(url);
// Header: title in the true centre, back control at least 44 by 44.
const header = await box(page, '.app-header');
const title = await box(page, '.app-header h1');
const back = await box(page, '.back');
assert.ok(Math.abs(title.x + title.w / 2 - (header.x + header.w / 2)) < 1, `title is not centred at ${width}px`);
assert.ok(back.w >= 44 && back.h >= 44, 'back control is at least 44 by 44');
assert.ok(Math.abs(back.y + back.h / 2 - (title.y + title.h / 2)) < 1, 'back and title share a centre line');
// Rows: every duration on one line, at the row's right padding.
const rows = await boxes(page, '.service-row');
const durations = await boxes(page, '.duration');
assert.equal(durations.length, 5);
durations.forEach((d, i) => {
assert.ok(Math.abs(d.right - (rows[i].right - 16)) < 1, `duration ${i + 1} is at the right edge`);
assert.ok(d.h < 25, `duration ${i + 1} is on one line`);
});
// Slots: all 80px wide, four per row at 390px, three at 320px.
const slots = await boxes(page, '.slots > li');
assert.equal(slots.length, 9);
assert.ok(slots.every((s) => Math.round(s.w) === 80), 'every slot is 5rem wide');
const morning = slots.slice(0, 5);
const firstRow = morning.filter((s) => Math.abs(s.y - morning[0].y) < 1).length;
assert.equal(firstRow, width === 390 ? 4 : 3, `slots per row at ${width}px`);
const sideways = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth);
assert.equal(sideways, false, `no sideways scrolling at ${width}px`);
if (width === 390) {
// The DevTools experiment: growing slots stretch the lone 11:00.
await page.addStyleTag({ content: '.slots > li { flex: 1 0 5rem; }' });
const grown = await boxes(page, '.slots > li');
assert.ok(grown[4].w > grown[0].w * 3, '11:00 stretches across its own row');
} else {
// Long text: the name and the title wrap, the duration and Back hold.
await page.locator('.service-name').last().evaluate((el) => { el.textContent = 'Medication review with the pharmacist, including repeat prescriptions'; });
await page.locator('.app-header h1').evaluate((el) => { el.textContent = 'Choose a time for your nurse appointment'; });
const name = await page.locator('.service-name').last().evaluate(rectOf);
const lastRow = await page.locator('.service-row').last().evaluate(rectOf);
const lastDuration = await page.locator('.duration').last().evaluate(rectOf);
assert.ok(name.h > 30, 'a long service name wraps');
assert.ok(lastDuration.h < 25 && Math.abs(lastDuration.right - (lastRow.right - 16)) < 1, 'the duration stays on one line at the right');
const longTitle = await box(page, '.app-header h1');
const backAfter = await box(page, '.back');
assert.ok(longTitle.h > 30 && longTitle.right <= header.right, 'a long title wraps inside the header');
assert.ok(backAfter.w >= 44 && backAfter.x >= header.x, 'Back keeps its size and place');
}
console.log(`PASS at ${width}px`);
await page.close();
}
await browser.close();
console.log('PASS: header, service rows and time slots');
JS
node test-layout.mjsThe test reads each element's position and size from the rendered page with getBoundingClientRect, the same numbers DevTools shows. It also repeats the two DevTools experiments: growing slots at 390 pixels, and a long service name and title at 320.
Check it worked
The output ends with three lines: PASS at 390px, PASS at 320px and PASS: header, service rows and time slots. To see the test catch a real mistake, change flex: 1 1 0 to flex: 1 1 auto in the header rule of style.css and run node test-layout.mjs again: it stops with an AssertionError whose message is title is not centred at 390px. Change it back and the test passes.
Step 9 · Clean up
When you have finished, remove the demo folder, including the Playwright install inside it:
cd ~
rm -rf ~/flexbox-demoPlaywright keeps its downloaded browsers in a shared cache (~/.cache/ms-playwright on Linux, ~/Library/Caches/ms-playwright on macOS). Leave it if other projects use Playwright; otherwise delete it to free a few hundred megabytes.
Check it worked
ls ~/flexbox-demo reports that there is no such file or directory.
Next steps
- Lay out a whole page, with regions placed by name and a card grid that lines up in columns: build page layouts with CSS Grid.
- Turn the column and wrapping patterns from this tutorial into reusable stack and cluster classes: build spacing utilities and a stack layout in CSS.
- Replace the placeholder buttons with real, accessible slots: build a time slot picker with radio buttons.
Part of these paths
Related tutorials
- How to Build Page Layouts with CSS GridYou will build a page with a header, sidebar, main area and footer using named grid areas, fill it with a grid of cards that adds and removes columns by itself, make one card span two columns, and change the layout for narrow screens.
- Build spacing utilities and a stack layout in CSSYou 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.
- Build a time slot picker with radio buttonsYou will build the Larkfield Clinic time slot picker from native radio buttons styled as chips, with a tick on the chosen time, taken slots that are announced and skipped, morning and afternoon groups, and a browser test that books 10:30 with the keyboard.
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