Flexbox for Rows, Columns and Alignment
Build and measure the two workhorse flex layouts, a row of cards that shares and wraps, and a fixed sidebar beside a fluid main area.
Contentsand lesson path
On this page
- The problem
- Step 1: a flex row sizes itself
- Step 2: share the row with flex: 1
- Step 3: wrap onto new lines
- Step 4: fixed sidebar, fluid main
- Measure the results
- Check your understanding
- Apply it
- Review prompt
Lessons of Responsive Layout with Flexbox & Grid
- Flexbox for Rows, Columns and Alignment Worked example · 25 min
- Grid for Pages and Card Collections Worked example · 25 min
- Mobile-First with Fluid Sizing, Media and Container Queries Concept · 25 min
- Serving the Right Image with srcset and sizes Concept · 15 min
- Lab: A Product Listing Page Without a Framework Lab · 30 min
- Check: Layout Challenges at Three Viewports Knowledge check · 8 questions
What you will learn
- Build one-dimensional layouts with flexbox: direction, wrapping, gap, alignment and flex-grow, flex-shrink and flex-basis.
Prerequisites: CSS Cascade & Box Model
01. The problem
Almost every interface is built from the same two arrangements: a row of similar items that must share the available width, and a shell with one fixed-width column beside one that takes the rest. This lesson builds both with flexbox and measures the result in a real browser, so the numbers you see are measured widths, not guesses.
Flexbox lays out items along one dimension, a row or a column. That one-dimensional view gives us the vocabulary for everything else in this skill. The main axis runs along the direction you chose with flex-direction; justify-content positions items along it. The cross axis runs perpendicular to it; align-items positions items along that one. A row laid out with flex-direction: row (the default) has a horizontal main axis and a vertical cross axis.
This lesson assumes you are comfortable with the box model and basic selectors from the CSS fundamentals skill: see /skills/css-fundamentals if you need a refresher first.
The worked example is a pricing page with three plan cards, followed by a sidebar shell. Create a folder with the two files below, plus a second page for the shell which step 4 introduces.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Flex rows</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Plans</h1>
<section class="row content" aria-label="Content-sized cards">
<article class="card">
<h2>Seed</h2>
<p>Small.</p>
</article>
<article class="card">
<h2>Team</h2>
<p>A little more text.</p>
</article>
<article class="card">
<h2>Company</h2>
<p>The longest plan description of the three cards.</p>
</article>
</section>
<section class="row even" aria-label="Equal cards">
<article class="card">
<h2>Seed</h2>
<p>Small.</p>
</article>
<article class="card">
<h2>Team</h2>
<p>A little more text.</p>
</article>
<article class="card">
<h2>Company</h2>
<p>The longest plan description of the three cards.</p>
</article>
</section>
<section class="row wrap" aria-label="Wrapping cards">
<article class="card">
<h2>Seed</h2>
<p>Everything one person needs to try the product.</p>
</article>
<article class="card">
<h2>Team</h2>
<p>Shared workspaces, roles and a shared activity feed.</p>
</article>
<article class="card">
<h2>Company</h2>
<p>Single sign-on, audit logs and a named contact.</p>
</article>
</section>
</body>
</html>* {
box-sizing: border-box;
}
body {
font: 16px/1.5 system-ui, sans-serif;
margin: 0;
padding: 16px;
}
.row {
display: flex;
gap: 16px;
margin-block: 16px;
}
.card {
border: 1px solid #666;
border-radius: 8px;
padding: 12px;
background: #fff;
}02. Step 1: a flex row sizes itself
Open index.html in a browser with the window about 900px wide. The first row of cards does not fill the page. Measured in headless Chromium (via Playwright 1.64.1), the three cards are 93, 166 and 406px wide, and the row leaves the rest of its 900px empty.
That is the default behaving correctly. Each flex item has flex-basis: auto, which means "start from my content size", and flex-shrink: 1, which only kicks in when the items together are too wide. With room to spare, items keep their content size and the leftover space simply stays empty. Nothing stretches to fill a flex row unless you ask for it.
Note gap: 16px rather than margins on the cards. The gap reserves a fixed channel between items, it never collapses, and it stays out of the cards themselves, so borders and backgrounds stay rectangular.
04. Step 3: wrap onto new lines
.wrap {
flex-wrap: wrap;
}
.wrap .card {
flex: 1 1 240px;
}The third row lets each card grow from a comfortable minimum of 240px but allows the line to break. At 560px the window body is 528px wide: one 240px card fits, two fit with the gap (496px), a third does not. Measured, the first line holds two cards of 256px and the third card takes 528px on a line of its own. At 320px every card gets a full line of 288px.
Cross-axis alignment now has a visible effect: cards on the same line share its height. The two cards on the first line both measure 166px tall although their text differs, because align-items: stretch is the default; the card alone on line two measures 142px. If you ever want top-aligned cards, that is align-items: flex-start.
The measurement also caught something the defaults cannot fix. At 320px the first two rows measure 93, 97 and 151px, and the whole page is 389px wide, so it scrolls sideways. With the default min-width: auto, a flex item does not shrink below its min-content size, here the largest unbreakable chunk of the card, the big heading word plus padding. flex: 1 cannot help, because no grow or shrink factor overrides that floor. Wrapping sidesteps it: each card moves to a line where its minimum fits. When a single row must never overflow, either wrap it or make sure every item can genuinely get small.
05. Step 4: fixed sidebar, fluid main
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sidebar shell</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<section class="shell a" aria-label="Sidebar shell, default shrinking">
<nav class="sidebar" aria-label="Sections">Sidebar</nav>
<main class="main">
https://example.com/a/very/long/path/that/never/wraps/because/it/is/one/word
</main>
</section>
<section class="shell b" aria-label="Sidebar shell, shrinkable main">
<nav class="sidebar" aria-label="Sections">Sidebar</nav>
<main class="main">
https://example.com/a/very/long/path/that/never/wraps/because/it/is/one/word
</main>
</section>
</body>
</html>.shell {
display: flex;
margin-block: 16px;
}
.sidebar {
flex: 0 0 240px;
padding: 12px;
background: #eee;
}
.shell .main {
flex: 1;
padding: 12px;
border: 1px solid #666;
}
.shell.b .main {
min-width: 0;
overflow-x: auto;
}The sidebar declares flex: 0 0 240px: do not grow, do not shrink, start from 240px. The main area takes flex: 1 and gets whatever is left. Both shells hold one long URL, a single unbreakable word.
At a 480px viewport, shell a keeps the sidebar at 240px but the main area measures 658px wide instead of the 208px it should get: the default min-width: auto floor is the width of that URL, so the item refuses to shrink below it and the page becomes 914px wide, scrolling sideways. Shell b adds min-width: 0, which withdraws the floor, and overflow-x: auto, which turns the overflow into a scrollable box. Now the main area measures 208px, the URL scrolls inside it, and the page stays at 480px.
The pair min-width: 0; overflow-x: auto on a flex child is one of the most useful two-line fixes in CSS: it is the answer whenever one stubborn piece of content, a URL, a code sample, a wide table, tries to widen the whole page.
06. Measure the results
Every number above came from the small script below, which drives headless Chromium through the Playwright test tooling (Playwright 1.64.1 with Chromium 156 here; the lab in this skill shows the full setup). You get the same figures by opening the pages and reading widths from the browser inspector, but a script makes the check repeatable, which is exactly what the final objective of this skill asks for.
import { chromium } from 'playwright';
import { pathToFileURL } from 'node:url';
const browser = await chromium.launch();
const page = await browser.newPage();
const rowsUrl = pathToFileURL('index.html').href;
const shellUrl = pathToFileURL('shell.html').href;
const widthsOf = (sel) =>
page.$$eval(sel, (els) =>
els.map((el) => Math.round(el.getBoundingClientRect().width)),
);
const rowReport = async (width) => {
await page.setViewportSize({ width, height: 900 });
await page.goto(rowsUrl);
const content = await widthsOf('.content .card');
const even = await widthsOf('.even .card');
const wrap = await widthsOf('.wrap .card');
const doc = await page.evaluate(() => document.documentElement.scrollWidth);
console.log(`${width}px content-sized: ${content.join(' / ')}`);
console.log(`${width}px flex: 1: ${even.join(' / ')}`);
console.log(`${width}px wrap 240px: ${wrap.join(' / ')}`);
console.log(`${width}px page width: ${doc}px (viewport ${width}px)`);
};
await rowReport(900);
await rowReport(560);
await rowReport(320);
await page.setViewportSize({ width: 560, height: 900 });
await page.goto(rowsUrl);
const heights = await page.$$eval('.wrap .card', (els) =>
els.map((el) => Math.round(el.getBoundingClientRect().height)),
);
console.log(`560px wrap heights: ${heights.join(' / ')}`);
await page.setViewportSize({ width: 480, height: 900 });
await page.goto(shellUrl);
for (const shell of ['a', 'b']) {
const other = shell === 'a' ? 'b' : 'a';
await page.$eval(`.shell.${shell}`, (el) => (el.style.display = 'flex'));
await page.$eval(`.shell.${other}`, (el) => (el.style.display = 'none'));
const main = await page.$eval(`.shell.${shell} .main`, (el) => ({
box: Math.round(el.getBoundingClientRect().width),
content: el.scrollWidth,
}));
const doc = await page.evaluate(() => document.documentElement.scrollWidth);
const line =
`480px shell ${shell}: main box ${main.box}px, ` +
`content ${main.content}px, page ${doc}px`;
console.log(line);
}
await browser.close();900px content-sized: 93 / 166 / 406
900px flex: 1: 279 / 279 / 279
900px wrap 240px: 279 / 279 / 279
900px page width: 900px (viewport 900px)
560px content-sized: 93 / 120 / 283
560px flex: 1: 165 / 165 / 165
560px wrap 240px: 256 / 256 / 528
560px page width: 560px (viewport 560px)
320px content-sized: 93 / 97 / 151
320px flex: 1: 93 / 97 / 151
320px wrap 240px: 288 / 288 / 288
320px page width: 389px (viewport 320px)
560px wrap heights: 166 / 166 / 142
480px shell a: main box 658px, content 656px, page 914px
480px shell b: main box 208px, content 656px, page 480px07. Check your understanding
08. Apply it
Take the product listing page you will build for this skill's practice task, or any small page of your own, and find three flex jobs in it:
- a header or toolbar row where the brand keeps its size and the actions share the rest, one
flex: 0 0 autoitem and oneflex: 1area; - a row inside each card, such as price and button, that wraps gracefully at 320px,
flex-wrap: wrapwith a basis you can defend; - any content that could overflow, such as a long product name, and give its container
min-width: 0with a scroll or a sensible break.
Measure the results at 900, 560 and 320px with the script pattern above, and check the page never scrolls sideways.
09. Review prompt
Without looking back: what does flex: 1 expand to, and how does that differ from flex: auto? Which property decides whether a flex row may break onto a second line, and what alignment makes cards on one line equally tall? What floor stops a flex item from shrinking, and which two declarations let a long URL scroll inside its own box instead of widening the page?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.