Frontend development · Intermediate · 18 min
Make components responsive with container queries
By Padding · Updated 18 Nov 2026
Modern browsers · CSS Containment Module Level 3 container queries · checked in Chromium 159
You will build one Larkfield Clinic appointment card that changes its layout to fit the space it is given, place it in a narrow sidebar and a wide main column on the same page, and prove with a Playwright script that it picks the right layout at six container widths and three screen sizes.
On this page
A media query asks one question: how wide is the browser window? That works for the page frame, but a component does not live in the window. It lives in a slot, and the same component can sit in a 288-pixel sidebar on a desktop and in a 668-pixel column on a tablet. A card styled by viewport width gets that backwards: on the desktop it thinks it has room, and on the tablet it thinks it does not.
Container queries ask a better question for components: how wide is the box I am in? You mark an element as a container with container-type, and rules inside @container apply according to that element's size. The card then carries its own responsive behaviour wherever you put it.
You will build the upcoming-appointment card from the Larkfield Clinic booking app, a fictional community clinic used across the design track. It shows the example booking, a Nurse appointment on Tuesday 9 December at 10:30, with two actions. The card appears twice on a "Your bookings" page: in the main column and in a "Next appointment" summary in the sidebar. By the end it has three layouts, chosen by the space each copy has, with no JavaScript.
Size container queries work in current Chrome, Edge, Firefox and Safari. MDN's compatibility table lists Chrome and Edge 105, Firefox 110 and Safari 16 as the first versions, all released by early 2023. You will write the card narrow-first, so an older browser, such as an outdated WebView on a low-end Android phone, ignores the @container rules and shows the stacked layout, which still works.
Step 1 · Set up the page and the clinic tokens
Make a demo folder with four files: the page, the Larkfield colour tokens, the page layout and (in the next step) the card. Start with the page. Both copies of the card are identical; each one sits in its own div class="appt-slot", which becomes the container later:
mkdir -p ~/container-queries-demo
cd ~/container-queries-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>Your bookings · Larkfield Clinic</title>
<link rel="stylesheet" href="tokens.css">
<link rel="stylesheet" href="page.css">
<link rel="stylesheet" href="card.css">
</head>
<body>
<div class="layout">
<main>
<h1>Your bookings</h1>
<div class="appt-slot">
<article class="appt">
<p class="appt-date"><span class="appt-day">Tue</span> <span class="appt-num">9</span> <span class="appt-month">Dec</span></p>
<div class="appt-body">
<h2 class="appt-title">Nurse appointment</h2>
<p class="appt-meta">10:30 · 15 min · Larkfield Clinic, 14 Mill Lane</p>
</div>
<div class="appt-actions">
<a href="#change">Change booking</a>
<a href="#cancel">Cancel booking</a>
</div>
</article>
</div>
</main>
<aside aria-labelledby="next-heading">
<h2 id="next-heading">Next appointment</h2>
<div class="appt-slot">
<article class="appt">
<p class="appt-date"><span class="appt-day">Tue</span> <span class="appt-num">9</span> <span class="appt-month">Dec</span></p>
<div class="appt-body">
<h3 class="appt-title">Nurse appointment</h3>
<p class="appt-meta">10:30 · 15 min · Larkfield Clinic, 14 Mill Lane</p>
</div>
<div class="appt-actions">
<a href="#change">Change booking</a>
<a href="#cancel">Cancel booking</a>
</div>
</article>
</div>
</aside>
</div>
</body>
</html>
HTMLThe sidebar copy uses an h3 because it sits under the sidebar's own h2. The heading level belongs to the page outline, not to the card, so it is the one thing that may differ between the two copies. The class names do not change, so the styles never depend on it.
Now the tokens, taken from the Larkfield high-fidelity design, and the page frame. The frame is the one place a media query belongs: above 52rem (832 pixels at the default text size) the page has a main column and an 18rem sidebar; below it, the sidebar drops under the main column.
cat > tokens.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-accent-tint: #e3f0ee;
}
CSS
cat > page.css <<'CSS'
* { box-sizing: border-box; }
body {
margin: 0;
padding: 1rem;
background: var(--colour-canvas);
color: var(--colour-text);
font-family: system-ui, sans-serif;
line-height: 1.5;
}
h1 { margin: 0 0 1rem; font-size: 1.75rem; line-height: 1.2; }
aside h2 { margin: 0 0 1rem; font-size: 1.25rem; line-height: 1.3; }
.layout {
display: grid;
gap: 1.5rem;
max-width: 64rem;
margin-inline: auto;
}
@media (min-width: 52rem) {
.layout { grid-template-columns: minmax(0, 1fr) 18rem; }
}
CSSCheck 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). With a wide window you see "Your bookings" on the left and "Next appointment" in a narrower column on the right, each with an unstyled card: a line reading "Tue 9 Dec", the heading, the details line and two underlined links. Narrow the window below about 830 pixels and "Next appointment" moves under "Your bookings".
Step 2 · Build the card for the narrowest space
Write the card's base styles for the smallest slot it will ever get: everything stacked in one column, the two actions side by side if they fit and wrapping if they do not. These rules apply everywhere, so this is also what browsers without container query support show.
cat > card.css <<'CSS'
/* Base: the narrowest layout, one column */
.appt {
display: grid;
grid-template-columns: 1fr;
gap: 0.75rem;
padding: 1rem;
background: var(--colour-surface);
border: 1px solid var(--colour-line);
border-radius: 0.75rem;
}
.appt-date {
margin: 0;
display: flex;
align-items: baseline;
gap: 0.375rem;
color: var(--colour-accent);
font-weight: 700;
}
.appt-day, .appt-month { font-size: 0.875rem; text-transform: uppercase; letter-spacing: 0.04em; }
.appt-num { font-size: 1.5rem; line-height: 1; }
.appt-title { margin: 0; font-size: 1.125rem; line-height: 1.3; }
.appt-meta { margin: 0.25rem 0 0; color: var(--colour-text-muted); font-size: 0.875rem; }
.appt-actions { display: flex; flex-wrap: wrap; gap: 0.5rem; }
.appt-actions a {
flex: 1 1 7rem;
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 2.75rem;
padding: 0 1rem;
border: 1px solid var(--colour-border);
border-radius: 0.5rem;
background: var(--colour-surface);
color: var(--colour-accent);
font-weight: 600;
text-decoration: none;
}
CSSgrid-template-columns: 1fr is written out even though one column is what a grid does by default. Naming it makes the three layouts easy to compare, both for you and for the test later. flex: 1 1 7rem gives each action a starting width of 7rem and lets it grow to share out any spare room on its row. The 7rem is not what decides when they wrap, though. A flex item has min-width: auto by default, so a button never shrinks below its label plus its padding and border, about 150 to 160 pixels for "Change booking" and "Cancel booking". When the row is narrower than both buttons and the gap, about 320 pixels, the second button wraps onto its own line instead of overflowing, and both stretch to the full width. min-height: 2.75rem keeps each one at least 44 pixels tall, a comfortable target for a thumb.
Check it worked
Reload. Both cards now have the same parts: a white box with a thin border, "TUE 9 DEC" in teal on the first line, the heading and details below it, and two outlined buttons. With a wide window, the main card's buttons share the last row, while the sidebar card's buttons sit one above the other, each the full width of the card: its slot is 288 pixels, which leaves about 254 inside the padding and border, too narrow for both labels side by side. Narrow the window to about 360 pixels and the main card's buttons stack too. Also with a wide window, the main column's card has a lot of empty space to the right of the details, because a stacked layout wastes a wide slot. That is what the next steps fix.
Step 3 · Measure the two slots
Before writing any query, find out how much space the card really gets in each place. Open your browser's developer tools (F12, or Cmd+Option+I on macOS), choose the Elements panel and hover over each div class="appt-slot": the overlay shows its size.
With the window 1280 pixels wide, the main column's slot is about 712 pixels wide and the sidebar's is 288. Now use the responsive device mode in DevTools to set the width to 700: the sidebar has dropped under the main column, so both slots are about 668 pixels wide. At 360, a typical small Android phone, both are 328.
Put those numbers side by side:
- At 1280, main 712 and sidebar 288.
- At 700, main 668 and sidebar 668.
- At 360, main 328 and sidebar 328.
The sidebar card has less room on a large desktop than on a tablet. Any rule written as @media (min-width: …) would give the sidebar card its wide layout on the desktop, where it is cramped, and its narrow layout on the tablet, where it has plenty of space. The card needs to respond to the slot.
Check it worked
You have three pairs of widths. The sidebar slot is narrower at 1280 than at 700, which is the case a viewport media query cannot handle.
Step 4 · Turn each slot into a container
A container is an ancestor whose size the card can query. Add one rule that makes every .appt-slot a container:
cat >> page.css <<'CSS'
/* Each slot is a size container the card can query */
.appt-slot { container: appt / inline-size; }
CSScontainer is a shorthand for two properties. container-name: appt gives the container a name, so the card's queries can target it on purpose rather than whatever container happens to be nearest. container-type: inline-size makes the element answer questions about its inline size, which is its width in a left-to-right or right-to-left language. It also applies size containment on that axis: the slot's width can no longer depend on its contents, which is what lets the browser lay out the slot first and the card inside it second, without going round in circles.
Three rules come with that:
- The container is the wrapper, not the card. An element cannot query its own size, which is why the markup has a slot around each card.
- The slot must get its width from its surroundings. Here it is a normal block inside a grid column, so it fills the column. If you put a container somewhere that sizes itself from its content, such as
width: fit-content, a float or aninline-block, it collapses to zero width, because its content no longer counts. - Use
inline-size, notsize, unless you also set a height.container-type: sizecontains both axes, so a container with no set height collapses to zero height.
Check it worked
Reload. Nothing looks different, which is expected: the slots now report their width, but no rule asks yet. In DevTools, select either div class="appt-slot" and look at the Styles panel: the container declaration is there and is not crossed out. In Chrome and Edge the element also shows a small container badge in the Elements panel.
Step 5 · Give the card a medium layout
Pick the first breakpoint from the card's content, not from a device list. Below about 384 pixels the details line wraps a lot and the buttons barely fit, so stacking is right. From 24rem (384 pixels) up, there is room to turn the date into a tile on the left, with the details and actions beside it:
cat >> card.css <<'CSS'
/* Medium: a date tile beside the details and actions */
@container appt (min-width: 24rem) {
.appt {
grid-template-columns: 4.5rem 1fr;
grid-template-areas:
"date body"
"date actions";
column-gap: 1rem;
}
.appt-date {
grid-area: date;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0;
padding: 0.5rem;
border-radius: 0.5rem;
background: var(--colour-accent-tint);
}
.appt-body { grid-area: body; }
.appt-actions { grid-area: actions; }
}
CSS@container appt (min-width: 24rem) reads "when the nearest ancestor container named appt is at least 24rem wide". It looks like a media query on purpose, and the same features work: min-width, max-width, orientation, and the range form (width >= 24rem). The rem here is the root font size, so a reader who raises their browser's text size gets the stacked layout sooner, which is what they need.
Check it worked
Reload with a 1280-pixel window. The main card now has a pale teal tile on the left with "TUE", a large "9" and "DEC" stacked in it, and the details and buttons to its right. The sidebar card, at 288 pixels, is still stacked. Same page, same viewport, two layouts. In device mode at 360 pixels, both cards are stacked; at 480, both have the tile.
Step 6 · Add a wide layout for roomy slots
At 36rem (576 pixels) there is room for everything on one row: the tile, the details, and the actions at the right edge. Add a second query after the first:
cat >> card.css <<'CSS'
/* Wide: one row, actions on the right */
@container appt (min-width: 36rem) {
.appt {
grid-template-columns: 4.5rem 1fr auto;
grid-template-areas: "date body actions";
align-items: center;
}
.appt-actions a { flex: 0 0 auto; }
}
CSSBoth queries match a 600-pixel slot, so the order matters. The wide rule comes later and wins where the two set the same property. The grid-area names from the medium rule still apply, so you only redraw the area picture. flex: 0 0 auto stops the buttons stretching, because the auto column already sizes itself to them.
If two areas of a page each need a different card arrangement, you do not need two components. You need two slot widths, and the card does the rest.
Check it worked
Reload at 1280. The main card is a single row: the date tile, then "Nurse appointment" with its details, then Change booking and Cancel booking side by side at the right. The sidebar card is still stacked. Switch device mode to 700: the sidebar has dropped below, and now both cards are single rows, because both slots are 668 pixels wide. At 360, both are stacked, and the page has no sideways scroll.
Step 7 · Test the card at several container widths
Resizing by hand is a good look, but a script proves the breakpoints exactly and can be rerun after any change. Install Playwright in the demo folder, pinned to a known version, and the Chromium build it drives:
cd ~/container-queries-demo
npm init -y > /dev/null
npm install --save-dev playwright@1.65.1
npx playwright install chromiumOn Linux, if Chromium will not start because of missing system libraries, run sudo npx playwright install-deps chromium once.
The script does two things. First it keeps the window at 1280 and changes only the width of the main column's slot, so the viewport never moves: if the card changes layout, the container did it. It checks each side of both breakpoints. Then it loads the page at three window widths and compares the two copies of the card. It counts the card's grid columns from the browser's computed style, which is one for stacked, two for medium and three for wide:
cat > test-cards.mjs <<'JS'
// Checks the appointment card's layout at exact container and window widths.
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
import { pathToFileURL } from 'node:url';
import { resolve } from 'node:path';
const url = pathToFileURL(resolve('index.html')).href;
const columns = (page, selector) => page.$eval(selector, (el) =>
getComputedStyle(el).gridTemplateColumns.split(' ').filter((t) => t.endsWith('px')).length);
const browser = await chromium.launch();
// 1. Same window, different container widths
const page = await browser.newPage({ viewport: { width: 1280, height: 800 } });
await page.goto(url);
const cases = [[280, 1], [383, 1], [384, 2], [575, 2], [576, 3], [700, 3]];
for (const [width, expected] of cases) {
await page.$eval('main .appt-slot', (el, w) => { el.style.width = `${w}px`; }, width);
const got = await columns(page, 'main .appt');
console.log(`container ${width}px: ${got} column(s)`);
assert.equal(got, expected, `container ${width}px should give ${expected} column(s)`);
}
await page.close();
// 2. Same card, two places, three window widths
for (const [width, mainCols, sideCols] of [[1280, 3, 1], [700, 3, 3], [360, 1, 1]]) {
const p = await browser.newPage({ viewport: { width, height: 800 } });
await p.goto(url);
const main = await columns(p, 'main .appt');
const side = await columns(p, 'aside .appt');
const sideways = await p.evaluate(() =>
document.documentElement.scrollWidth > document.documentElement.clientWidth);
console.log(`window ${width}px: main ${main}, sidebar ${side}`);
assert.equal(main, mainCols, `main card at window ${width}px`);
assert.equal(side, sideCols, `sidebar card at window ${width}px`);
assert.equal(sideways, false, `no sideways scroll at window ${width}px`);
await p.close();
}
await browser.close();
console.log('All container checks passed');
JS
node test-cards.mjsThe pairs 383 and 384, and 575 and 576, sit one pixel either side of each breakpoint. min-width includes its value, so 384 is already medium. Testing both sides catches an off-by-one error the moment someone changes a breakpoint.
Check it worked
The script prints this and exits without an error:
container 280px: 1 column(s)
container 383px: 1 column(s)
container 384px: 2 column(s)
container 575px: 2 column(s)
container 576px: 3 column(s)
container 700px: 3 column(s)
window 1280px: main 3, sidebar 1
window 700px: main 3, sidebar 3
window 360px: main 1, sidebar 1
All container checks passedThe window 1280 line is the point of the tutorial: one viewport, two layouts of the same card. If an assertion fails, the message names the width and the card. The usual cause is a slot that is not a container (check the container rule in page.css) or a query whose name does not match the container's name: a query for a name that no ancestor has never matches.
Troubleshooting
If every count is 1, open DevTools on the main slot and check that the container declaration is applied. If counts are right in Chromium but you see something else in another browser, check its version against the MDN compatibility table for @container. Container queries only exist from the versions listed there; earlier versions show the stacked layout by design.
Step 8 · Clean up
Remove the demo folder, including the Playwright package installed in it:
cd ~
rm -rf ~/container-queries-demoPlaywright also 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 that folder too to get the space back.
Next steps
- The card's actions row is a flexbox. Lay out components with Flexbox covers wrapping, growing and shrinking in depth.
- Container queries handle the component; the page frame still needs breakpoints. Build a responsive page from a Figma frame builds the full Pick a time page at phone, tablet and desktop sizes.
- Container query units such as
cqi(1% of the container's inline size) work withclamp()the wayvwdoes. Build fluid type with CSS clamp() shows the method; swapvwforcqito size a card's heading by its slot. - For the grid behind the page frame, see How to build page layouts with CSS Grid.
Part of these paths
Related tutorials
- 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.
- Build a responsive page from a Figma frameYou will build the Larkfield Clinic Pick a time screen as one responsive page from its phone, tablet and desktop frames, with values mapped to tokens, breakpoints taken from the design note, and a script that screenshots and measures the page at each width.
- 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.
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