Testing responsive layouts from 360 to 1920 pixels
Derive a width sweep from your own CSS breakpoints, assert no horizontal scroll and 24 px targets in Playwright, and keep screenshots to a reviewed handful.
Responsive bugs rarely sit at "mobile, tablet, desktop". They sit one pixel either side of a media query, where a card grid wraps late, or at the width where one long word no longer fits in a heading. A test that visits three fixed widths cannot see either. This walkthrough builds a layered check for a site you build yourself: a sweep whose widths come from the stylesheet's own breakpoints, a rule check for tap targets, a few reviewed screenshots and a short manual pass. The automated parts are Playwright.
I wrote my own version after a beta tester sent me a screenshot of a button sitting half outside the screen on a narrow phone. Until then my method for calling an app responsive was resizing my own browser window on whichever pages I happened to be working on.
Why the range starts at 320#
The lowest width in the sweep is not arbitrary. WCAG 2.2 success criterion 1.4.10, Reflow (level AA), requires that vertically scrolling content can be presented without loss of information or functionality, and without two-dimensional scrolling, at a width equivalent to 320 CSS pixels. The Understanding page explains that this is a 1280 pixel viewport at 400 percent zoom, which is how a low-vision user ends up there. Content that needs two dimensions, such as data tables, maps and diagrams, is exempt.
So a sweep that starts at 320 covers both the smallest phones and a legal-grade accessibility requirement with one assertion. The top of the range is a monitor-sized 1920, where the failure is the opposite one: a layout that stretches instead of stopping at a sensible measure.
Take the widths from the CSS#
A fixed step, such as every 40 pixels, samples the range evenly and still misses the pixel that matters. A media query switches at an exact width, and the classic bug is an off-by-one: (min-width: 640px) applies at 640 and not at 639, so one of the two layouts is only visible at one of two pixels. The widths worth testing are therefore a property of the stylesheet, and the test should read them from it.
Chrome exposes the rules to script through document.styleSheets. The helper below collects every width in a media query, converts rem and em to pixels (browsers evaluate them against the initial font size of 16 pixels in media queries), and returns the sweep:
import type { Page } from "@playwright/test";
/** Widths mentioned in width-based media queries of the page's own stylesheets. */
export async function breakpoints(page: Page): Promise<number[]> {
return page.evaluate(() => {
const found = new Set<number>();
const walk = (rules: CSSRuleList) => {
for (const rule of Array.from(rules)) {
if (rule instanceof CSSMediaRule && /width/.test(rule.conditionText)) {
for (const m of rule.conditionText.matchAll(/(\d+(?:\.\d+)?)(px|rem|em)\b/g)) {
found.add(Math.round(parseFloat(m[1]) * (m[2] === "px" ? 1 : 16)));
}
}
if ("cssRules" in rule) walk((rule as CSSGroupingRule).cssRules);
}
};
for (const sheet of Array.from(document.styleSheets)) {
try {
walk(sheet.cssRules);
} catch {
// cross-origin stylesheet: its rules are not readable, and not yours to test
}
}
return [...found];
});
}
/** Each breakpoint and its neighbours, midpoints between them, and a coarse net. */
export function sweepWidths(bps: number[], min = 320, max = 1920): number[] {
const anchors = [...new Set([min, ...bps.filter((b) => b > min && b < max), max])].sort((a, b) => a - b);
const out = new Set<number>();
for (const b of bps) for (const w of [b - 1, b, b + 1]) out.add(w);
for (let i = 0; i < anchors.length - 1; i++) out.add(Math.round((anchors[i] + anchors[i + 1]) / 2));
for (let w = min; w <= max; w += 100) out.add(w);
anchors.forEach((a) => out.add(a));
return [...out].filter((w) => w >= min && w <= max).sort((a, b) => a - b);
}Three groups of widths come out of it. Each breakpoint and its two neighbours cover the off-by-one cases, since a min-width query changes between b - 1 and b and a max-width query between b and b + 1. The midpoint between every pair of neighbouring breakpoints catches layouts that are only fragile in the middle of a range, where text has the least room before the next query rescues it. The 100 pixel net catches whatever neither anticipated. None of this is proof: a sweep samples the width axis and cannot find a bug that needs one specific width nobody listed. It reliably finds the bugs that line up with the CSS, and those are most of them.
Container queries are not covered by this, because they depend on a component's width and not the viewport's. If you rely on them heavily, add the component's own container widths to the list by hand.
Assert that nothing scrolls sideways#
The assertion is that the document is not wider than the viewport. A 400 pixel wide block in a 320 pixel viewport makes document.documentElement.scrollWidth 400 while clientWidth stays 320, so comparing the two separates a broken layout from a healthy one.
A bare number is a poor failure message, so the test also names suspects:
import { test, expect, type Page } from "@playwright/test";
import { breakpoints, sweepWidths } from "./widths";
const PAGES = ["/", "/articles", "/about"];
// Elements whose right edge is past the viewport: the usual suspects.
async function overflowing(page: Page) {
return page.evaluate(() => {
const vw = document.documentElement.clientWidth;
return [...document.querySelectorAll("body *")]
.filter((el) => el.getBoundingClientRect().right > vw + 1)
.slice(0, 5)
.map((el) => `${el.tagName.toLowerCase()}.${el.className}`.slice(0, 80));
});
}
for (const path of PAGES) {
test(`no horizontal scroll: ${path}`, async ({ page }) => {
await page.goto(path);
for (const width of sweepWidths(await breakpoints(page))) {
await page.setViewportSize({ width, height: 900 });
const { sw, cw } = await page.evaluate(() => ({
sw: document.documentElement.scrollWidth,
cw: document.documentElement.clientWidth,
}));
expect(sw, `${path} at ${width}px overflows: ${(await overflowing(page)).join(", ")}`).toBeLessThanOrEqual(cw);
}
});
}Because the viewport changes inside one test, one browser project is enough, and no navigation happens between resizes, so the cost of the sweep is the resizes and not page loads. A failure that reads /articles at 440px overflows: pre.code-block is a five-minute fix, while "expected 452 to be at most 440" is an investigation.
The helper reports every element that extends past the viewport, including ones inside a container that scrolls on purpose, such as a code block with overflow-x: auto. That is why the assertion is on the document and the helper only names suspects.
On my project the useful result of the first full audit was not the bug list but the clustering. Page after page failed for the same few upstream reasons: a shared container that did not constrain its width, a settings-row primitive that could not wrap, and floating elements that each assumed they were alone in the same corner. Fixing those components removed dozens of per-page symptoms at once, so I now trace each violation to the primitive behind it, fix it there and re-run the sweep. That audit covered a couple of dozen routes at 360, 390, 768, 1024, 1440 and 1920 pixels, hundreds of route-and-width runs that take more than five minutes end to end, and the final pass counted zero violations rather than merely looking fine.
Test with the content you will really publish#
Short placeholder text passes layouts that real content breaks. Point the sweep at pages with the longest title you have, a long unbroken URL in a paragraph and, if the site is translated, the longest language, as in eight languages, one developer. The usual culprits are all content-driven:
- A flex or grid child with long unbreakable content will not shrink below its content width unless it has
min-width: 0. - Long URLs and identifiers need
overflow-wrap: anywhereon their container. - A table or code block wider than the column needs its own scroll container.
Loading states need the same scrutiny, because a page can be sound once data arrives and still jump, flash or overflow in the second before. The sweeps turned up skeletons sized for desktop, placeholders that reserved the wrong space, and promo panels that rendered before the query gating them had resolved. My rule since then is that the loading UI mirrors the arrival state at every width.
Beware of the fix that makes the test green#
Setting overflow-x: hidden on body makes the sweep pass and the page broken, because content is clipped instead of reachable. Treat any such rule as a smell. Fix the element that overflows, and if clipping is genuinely right, do it on one specific container.
Check target size as a rule#
Overflow is a failure you can detect without knowing the design. Some accessibility rules are mechanical too. WCAG 2.2 success criterion 2.5.8, Target Size (Minimum), level AA, requires pointer targets of at least 24 by 24 CSS pixels. The Understanding page lists exceptions: an undersized target passes if a 24 pixel circle centred on it does not touch another target, if an equivalent control exists, if the target is inline in a sentence, if the browser controls its size, or if the presentation is essential. A blanket test is therefore stricter than the standard, which is acceptable for buttons and form controls if inline text links are left out:
import { test, expect } from "@playwright/test";
for (const width of [360, 768, 1440]) {
test(`controls are at least 24px at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height: 900 });
await page.goto("/");
const small: string[] = [];
for (const el of await page.locator("button, input:not([type=hidden]), select, summary").all()) {
const box = await el.boundingBox();
if (box && (box.width < 24 || box.height < 24)) {
small.push(`${await el.evaluate((n) => n.outerHTML.slice(0, 60))} (${Math.round(box.width)}x${Math.round(box.height)})`);
}
}
expect(small).toEqual([]);
});
}It measures the rendered box, so it also catches a designer shrinking an icon button on mobile. Visually hidden checkboxes wrapped by a custom control show up as false positives; exclude them by selector rather than weakening the rule.
Rules of this kind share a pattern, and each fails with a number. Assert that the primary call to action sits inside the first viewport height at 360 pixels. Assert that a sticky header leaves a minimum share of the screen for content. Assert that the computed font size of body text never falls below the minimum you chose. My own floor for touch targets is 44 pixels, stricter than the 24 pixel standard, and I wrote the violation classes down (horizontal overflow, unusable controls, unreadable text, colliding layers such as banners, modals and floating buttons) in the project's engineering docs, so new UI is built against them instead of being argued per pull request.
Keep screenshots few and reviewed#
Screenshots catch what no rule describes, such as spacing and alignment. The Playwright snapshot documentation warns that rendering varies with the host operating system and settings, and recommends generating baselines in the environment that later compares them. In practice that means producing them in CI, in the same container image, not on a laptop.
import { test, expect } from "@playwright/test";
for (const colorScheme of ["light", "dark"] as const) {
for (const width of [360, 768, 1440]) {
test(`home at ${width}px, ${colorScheme}`, async ({ page }) => {
await page.emulateMedia({ colorScheme });
await page.setViewportSize({ width, height: 900 });
await page.goto("/");
await expect(page).toHaveScreenshot(`home-${width}-${colorScheme}.png`, {
fullPage: true,
maxDiffPixelRatio: 0.01,
mask: [page.locator("[data-dynamic]")],
});
});
}
}mask covers volatile regions such as dates and counters; maxDiffPixelRatio is a value between 0 and 1 that you tune, since too loose a threshold hides regressions and too strict a one produces noise. Six screenshots for one page is already plenty to look at when they change, so restrict this layer to pages where appearance is the product, such as the home page and an article page. The sweep and the rule checks cover the rest. When screenshots flake, the usual causes are fonts that load late, images that decode at different times and animation; wait for fonts and images before capturing.
Do the manual pass that no script replaces#
Emulation proves the CSS is sound. It does not reproduce the toolbars of a mobile browser that change the viewport height, notches and safe areas, or touch behaviour. Before a release, three checks cover that. Zoom the browser to 400 percent at a 1280 pixel window and scroll the main flow, which reproduces the reflow requirement the way a user meets it. Open the site on a real phone, where tap targets, the on-screen keyboard and dynamic toolbars behave differently from an emulated viewport. And walk the main flow with the keyboard only, watching that focus stays visible and is never hidden behind a sticky header. My routine is to automate the matrix for every change and walk the critical flows on a couple of physical devices before anything goes to testers, because a headless run at 390 pixels does not show what a collapsing toolbar does to fixed-position elements, how a notch inset eats a corner button, or how a real touch keyboard reflows a form.
One last viewport trap belongs in that manual pass. Layouts built on 100vh can be taller than the visible area while browser toolbars are showing, so test them on a real device and prefer layouts that do not depend on the exact viewport height.
What each layer is for#
If the site is a handful of static pages that change twice a year, the sweep alone is enough, and screenshots are overhead. If a design system already has component-level visual tests, do not repeat them at page level; keep the sweep and the manual pass. If the product is a dense desktop-only tool with a stated minimum window, test from that width up and say so in the documentation. For everything else, the order of value is the one used here: the sweep first because it fails loudly on the worst problem, rule checks second because they cost a few lines each, screenshots last because every baseline is something a person must keep reviewing.
Related articles
All articles →A nonce gives a strict script policy but ends static rendering; a static header keeps pages cached but needs unsafe-inline. How to choose on a Next.js 16 site.
11 min
Design for a site in eight languages with one maintainer: next-intl routing, ICU plurals, CI checks for broken messages, stale-translation tracking, hreflang.
13 min
Register a denied Consent Mode v2 default ahead of the AdSense script in Next.js, let a certified CMP send the updates, and check the order in the browser.
12 min