Frontend Fundamentals: HTML, CSS, and Responsive Styling Questions
Core web-platform implementation skills: semantic HTML and document structure, native controls versus ARIA-patched divs (button versus link), accessible markup (labels, headings, landmarks, image alt text, icon-only buttons, keyboard operability, skip links, ARIA basics, focus styles), the CSS box model, cascade and specificity (including cascade layers and taming !important), selector matching cost, display types, positioning (static, relative, absolute, fixed, sticky) and stacking contexts and z-index, flexbox and grid layout (including subgrid and masonry options), units and fluid sizing (rem, clamp, viewport units including dynamic viewport units), the viewport meta tag, media queries, mobile-first breakpoints and how to choose them, container queries, responsive images (srcset, sizes, picture, aspect-ratio), touch target sizing, right-to-left and long-text layouts, custom properties and light/dark theming, and CSS organization (BEM, CSS Modules, utility-first, Sass). Includes debugging layout bugs, progressive enhancement, @supports and cross-engine CSS fallbacks. Performance measurement, building full interactive widgets and form flows, design-system governance, WCAG audit strategy, design handoff, visual regression testing and cross-browser test coverage are covered elsewhere.
You have a horizontal navigation bar with an unordered list. The design requires items to be centered vertically and spaced evenly across the width; on narrow screens the items should wrap onto multiple lines. Given this HTML:
<nav class='nav'><ul class='nav__list'><li class='nav__item'>Home</li><li class='nav__item'>Products</li><li class='nav__item'>About</li></ul></nav>
Write the CSS (using Flexbox) to achieve the design and explain how to make wrapping work correctly.
Sample Answer
Direct answer
Make the ul the flex container (the element with display: flex, whose children become flex items). Three declarations do the design: justify-content: space-evenly spaces the items evenly along the row, align-items: center centres them vertically, and flex-wrap: wrap lets them move onto further lines when the row is too narrow. Wrapping works because a flex container defaults to a single line; flex-wrap: wrap is the switch that allows several lines, and each line is then spaced on its own.
The CSS
body { margin: 0; font: 16px/1.5 sans-serif; }
.nav__list {
display: flex;
flex-wrap: wrap;
justify-content: space-evenly;
align-items: center;
row-gap: 0.5rem;
min-height: 80px;
margin: 0;
padding: 0;
list-style: none;
}
.nav__item { padding: 0.5rem 2rem; background: #eee; }
What each line does:
| Declaration | Axis | Effect |
|---|---|---|
display: flex | n/a | ul becomes the flex container; the three li become flex items in a row (the default flex-direction is row, so the main axis, the direction items are laid out in, is horizontal) |
justify-content: space-evenly | main (horizontal) | The same amount of space before the first item, between each pair, and after the last |
align-items: center | cross (vertical) | Each item is centred inside its flex line instead of stretching to fill it |
min-height: 80px | cross | Gives the line room to centre in. On a one-line container the line is only as tall as its tallest item, so without extra height there is nothing to centre against |
flex-wrap: wrap | main | Allows several flex lines; an item that does not fit starts the next line |
row-gap: 0.5rem | cross | Space between wrapped lines |
list-style: none; margin: 0; padding: 0 | n/a | Removes the bullets and the default indent of the ul |
Why wrapping needs flex-wrap
With the default flex-wrap: nowrap the container keeps everything on one line. Items are squeezed as far as their content allows, and past that the row overflows the container instead of breaking. Deleting flex-wrap: wrap from the demo below makes the narrow-screen check fail. With wrap, items are placed on a line until the next one would not fit, then a new line starts, and justify-content is applied to every line separately. A lone item on the last line is therefore centred rather than left-aligned.
How space-evenly differs from space-around and space-between
All three divide the free space F, the row width left over after the items are laid out. With three items, space-between puts nothing at the ends and splits F into 2 slots between the items (F/2 each). space-around gives every item half a slot on each side, so the ends get F/6 and the space between two items is F/3 (two halves). space-evenly makes n + 1 = 4 equal slots of F/4: the same space before, between and after. In the Chromium sample run below, F is 460.4px (800px minus the three item widths): F/4 = 115.1, F/6 = 76.7, F/3 = 153.5 and F/2 = 230.2, which are the values the script prints for each keyword. Only space-evenly makes the ends equal to the gaps between items.
Pitfall: gap breaks "evenly"
gap is taken out of the free space first and then added back between the items, so with space-evenly the spaces between items end up larger than the spaces at the ends. The script's last line per engine adds column-gap: 16px. The two 16px gaps remove 32px from F, so each of the four slots shrinks by 8px (115.1 to 107.1 in Chromium), and each space between items then gains the 16px gap back (107.1 + 16 = 123.1). The ends are 107.1px, the spaces between items are 123.1px, and the difference is exactly the 16px column gap in every engine (the absolute numbers differ by engine only because the font widths differ). Use row-gap alone (as above) when the horizontal spacing must be equal.
Worked example, checked in three browsers
The script loads the HTML from the question with the CSS above, then measures real boxes. run applies a stylesheet at 800px and at 220px wide and returns the names of the assertions that fail: one row at 800px, equal space before, between and after the items, items not stretched to the list's height, items vertically centred, wrapping onto several rows at 220px, and no sideways overflow at 220px. The script first runs the full stylesheet (which must fail nothing), then removes each of the three declarations in turn, then prints how the three spacing keywords and a column gap divide the row.
import { chromium, firefox, webkit } from 'playwright';
import assert from 'node:assert/strict';
const css = `
body { margin: 0; font: 16px/1.5 sans-serif; }
.nav__list {
display: flex;
flex-wrap: wrap;
justify-content: space-evenly;
align-items: center;
row-gap: 0.5rem;
min-height: 80px;
margin: 0;
padding: 0;
list-style: none;
}
.nav__item { padding: 0.5rem 2rem; background: #eee; }
`;
const html = (sheet) => `<!doctype html><style>${sheet}</style>
<nav class='nav'><ul class='nav__list'><li class='nav__item'>Home</li><li class='nav__item'>Products</li><li class='nav__item'>About</li></ul></nav>`;
const measure = (page) => page.evaluate(() => {
const r = (e) => e.getBoundingClientRect();
return { list: r(document.querySelector('.nav__list')), items: [...document.querySelectorAll('.nav__item')].map(r) };
});
// Space before the first item, between each pair, and after the last, along the row.
const spaces = ({ list, items }) => [items[0].left - list.left, items[1].left - items[0].right, items[2].left - items[1].right, list.right - items[2].right];
// Run every assertion against one stylesheet and return the names of the ones that fail.
async function run(page, sheet) {
await page.setViewportSize({ width: 800, height: 600 });
await page.setContent(html(sheet));
let { list, items } = await measure(page);
const gaps = spaces({ list, items });
const failed = [];
if (new Set(items.map((i) => i.top)).size !== 1) failed.push('one row at 800px');
if (!gaps.every((g) => Math.abs(g - gaps[0]) < 0.5)) failed.push('even spacing');
if (!items.every((i) => i.height < list.height)) failed.push('items not stretched');
if (!items.every((i) => Math.abs((i.top + i.bottom) / 2 - (list.top + list.bottom) / 2) < 0.5)) failed.push('vertically centred');
await page.setViewportSize({ width: 220, height: 600 });
({ list, items } = await measure(page));
const rows = new Set(items.map((i) => i.top)).size;
if (rows < 2) failed.push('wraps at 220px');
if (!(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth))) failed.push('no overflow at 220px');
return { failed, rows };
}
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const page = await browser.newPage();
const full = await run(page, css);
assert.deepEqual(full.failed, [], 'the full stylesheet passes every assertion');
console.log(name, 'full css: failed [none] | rows at 220px:', full.rows);
for (const decl of ['flex-wrap: wrap;', 'justify-content: space-evenly;', 'align-items: center;']) {
const res = await run(page, css.replace(decl, ''));
assert.ok(res.failed.length > 0, decl + ' is doing work');
console.log(name, `without "${decl}": failed [${res.failed.join(', ')}]`);
}
// How the three spacing values divide the same free space at 800px, and what a column gap adds.
await page.setViewportSize({ width: 800, height: 600 });
const row = (sheet) => page.setContent(html(sheet)).then(() => measure(page)).then(spaces);
const fmt = (s) => `ends ${s[0].toFixed(1)}/${s[3].toFixed(1)}, between ${s[1].toFixed(1)}/${s[2].toFixed(1)}`;
for (const value of ['space-evenly', 'space-around', 'space-between']) {
console.log(name, `${value}: ${fmt(await row(css.replace('space-evenly', value)))}`);
}
console.log(name, `space-evenly with column-gap: 16px: ${fmt(await row(css + '.nav__list { column-gap: 16px; }'))}`);
await browser.close();
}
Printed output (the item widths, and so the decimals, differ by engine because of the fonts):
chromium full css: failed [none] | rows at 220px: 3
chromium without "flex-wrap: wrap;": failed [wraps at 220px, no overflow at 220px]
chromium without "justify-content: space-evenly;": failed [even spacing]
chromium without "align-items: center;": failed [items not stretched]
chromium space-evenly: ends 115.1/115.1, between 115.1/115.1
chromium space-around: ends 76.7/76.7, between 153.5/153.5
chromium space-between: ends 0.0/0.0, between 230.2/230.2
chromium space-evenly with column-gap: 16px: ends 107.1/107.1, between 123.1/123.1
firefox full css: failed [none] | rows at 220px: 3
firefox without "flex-wrap: wrap;": failed [wraps at 220px, no overflow at 220px]
firefox without "justify-content: space-evenly;": failed [even spacing]
firefox without "align-items: center;": failed [items not stretched]
firefox space-evenly: ends 116.5/116.5, between 116.5/116.5
firefox space-around: ends 77.7/77.7, between 155.4/155.4
firefox space-between: ends 0.0/0.0, between 233.0/233.0
firefox space-evenly with column-gap: 16px: ends 108.5/108.5, between 124.5/124.5
webkit full css: failed [none] | rows at 220px: 3
webkit without "flex-wrap: wrap;": failed [wraps at 220px, no overflow at 220px]
webkit without "justify-content: space-evenly;": failed [even spacing]
webkit without "align-items: center;": failed [items not stretched]
webkit space-evenly: ends 115.8/115.8, between 115.8/115.8
webkit space-around: ends 77.2/77.2, between 154.3/154.3
webkit space-between: ends 0.0/0.0, between 231.5/231.5
webkit space-evenly with column-gap: 16px: ends 107.8/107.8, between 123.8/123.8
The full stylesheet fails no assertion: at 800px the three items share one row with equal space before, between and after them, and each is centred in the 80px-tall list; at 220px the same CSS gives three rows. Each removal fails a different assertion. Without flex-wrap: wrap the items cannot wrap, so the wrapping and overflow checks fail at 220px. Without justify-content: space-evenly the items pack to the start and the spacing is no longer even. Without align-items: center the items stretch to the full 80px, so the not-stretched check fails (stretched items still share the list's midline, so the centring check alone would not catch it).
Trade-offs and edge cases
- Wrapping puts items on a new line at whatever width forces it, not at a designed breakpoint. If the design needs a specific narrow layout (a menu button, for example), use a media query for that and keep
flex-wrapas the safety net. - If the items must also grow to fill each row,
flex: 1 1 autoon.nav__itemdoes that, but it replaces the even spacing with wider items, which is a different design. - A real navigation bar puts links (
a) inside theli; the padding then belongs on theaso the whole padded area is clickable.
Running the code
mkdir demo && cd demo
echo '{"type":"module"}' > package.json
npm i playwright@1.48.2 && npx playwright install chromium firefox webkit
# save the script as nav.mjs
node nav.mjs
The output above comes from the mcr.microsoft.com/playwright:v1.48.2-jammy image, which bundles Playwright's Chromium, Firefox and WebKit builds. Playwright's WebKit is an engine build used for testing, not Safari on a device.
Write plain CSS (no frameworks) for a responsive, mobile-first centered container. Requirements: container should be fluid on small screens, have width:100% up to a max-width of 1200px on large screens, be horizontally centered, include 16px side padding on small screens and 32px side padding on screens >= 768px. Provide the CSS rules only.
Sample Answer
The CSS
.container {
box-sizing: border-box; /* width and max-width include the padding */
width: 100%; /* fluid: follows the viewport on small screens */
max-width: 1200px; /* stops growing here on large screens */
margin-inline: auto; /* centres the box once it is narrower than its parent */
padding-inline: 16px; /* small screens (mobile-first default) */
}
@media (min-width: 768px) {
.container { padding-inline: 32px; } /* 768px and wider */
}
That is the whole answer: one base rule that is correct for the smallest screens, and one min-width media query that overrides a single property. "Mobile-first" means exactly this: the unconditioned rules describe the small layout and queries only add changes as the screen grows.
Why each line is there
width: 100%plusmax-width: 1200px: the box is as wide as its parent until the parent exceeds 1200px, then it stops. (max-widthcaps a width that would otherwise be larger.)margin-inline: auto: on a block that is narrower than its parent (here becausemax-widthcaps it), automatic left and right margins split the leftover space equally, which centres the box. When the box fills the parent there is no leftover space, so the margins resolve to 0 and nothing looks different.margin-inlineis the logical shorthand for the margins at the start and end of the line direction: left and right in a left-to-right language such as English, right and left in a right-to-left one such as Arabic. (padding-inlineworks the same way for padding.)padding-inline: 16px by default, 32px from 768px up. The query ismin-width: 768px(matches 768 and wider), so the mobile range is "below 768px" with no gap and no overlap. Writing the mobile range asmax-width: 767pxleaves a hole for viewports with fractional widths such as 767.5px.box-sizing: border-box: the one line people forget. The defaultcontent-boxapplieswidthto the content only, sowidth: 100%plus 32px of padding on each side makes the box 64px wider than its parent and produces a horizontal scrollbar. Withborder-boxthe width includes padding, so100%really means "fit the parent".
A decision the wording leaves open
"max-width of 1200px" can mean the whole box (padding included) or the text column. Here the whole box is capped, so the content column is 1200 - 2 x 32 = 1136px on large screens. If the design wants a 1200px content column, change max-width to calc(1200px + 2 * 32px) (1264px). State which one you chose.
Fluid padding instead of two steps
The padding can shrink smoothly rather than jump at 768px:
.container { padding-inline: clamp(16px, 4.1667vw, 32px); }
clamp(min, preferred, max) uses the preferred value but never goes below the minimum or above the maximum. 1vw is 1% of the viewport width, and 4.1667vw is 32px at a 768px viewport, so the padding is 16px at and below 384px, grows linearly, and is 32px from 768px up. This replaces the media query, so it is a different behaviour from the stepped version, not an addition.
Checking it in real browsers
The script below loads the stepped rules in Chromium, Firefox and WebKit, reads getBoundingClientRect and getComputedStyle at seven viewport widths, and compares each to the value derived by hand (width is the smaller of the viewport and 1200; padding is 16 below 768 and 32 from 768; the left edge is half the leftover space). Setting DROP_BOX_SIZING=1 removes the box-sizing line to prove the check can fail.
import { chromium, firefox, webkit } from 'playwright';
let css = `
.container {
box-sizing: border-box;
width: 100%;
max-width: 1200px;
margin-inline: auto;
padding-inline: 16px;
}
@media (min-width: 768px) {
.container { padding-inline: 32px; }
}
.fluid { padding-inline: clamp(16px, 4.1667vw, 32px); }
`;
if (process.env.DROP_BOX_SIZING) css = css.replace('box-sizing: border-box;', '');
const page = `<!doctype html><meta name=viewport content="width=device-width">
<style>body{margin:0}${css}</style>
<div class="container" id="c"><p>Content</p></div>
<div class="container fluid" id="f"><p>Fluid</p></div>`;
let bad = 0;
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const p = await browser.newPage();
for (const w of [320, 375, 767, 768, 1200, 1440, 1920]) {
await p.setViewportSize({ width: w, height: 800 });
await p.setContent(page);
const r = await p.evaluate(() => {
const el = document.getElementById('c'), cs = getComputedStyle(el);
const root = document.documentElement, box = el.getBoundingClientRect();
return { vw: root.clientWidth, width: box.width, left: box.left,
pad: parseFloat(cs.paddingLeft), overflow: root.scrollWidth > root.clientWidth };
});
const width = Math.min(r.vw, 1200), pad = r.vw >= 768 ? 32 : 16;
const pass = r.width === width && r.pad === pad && r.left === (r.vw - width) / 2 && !r.overflow;
if (!pass) bad++;
if (name === 'chromium' || !pass)
console.log(name.padEnd(8), String(w).padStart(4), `width=${r.width} left=${r.left} pad=${r.pad} overflow=${r.overflow}`, pass ? 'ok' : 'FAIL');
}
for (const [w, want] of [[384, 16], [576, 24], [768, 32]]) {
await p.setViewportSize({ width: w, height: 800 });
await p.setContent(page);
const pad = await p.evaluate(() => parseFloat(getComputedStyle(document.getElementById('f')).paddingLeft));
const ok = Math.abs(pad - want) < 0.01; // 4.1667vw is 16.0001px at 384 and 32.0002px at 768
if (!ok) bad++;
if (name === 'chromium' || !ok) console.log('fluid ', String(w).padStart(4), `pad=${pad.toFixed(2)}`, ok ? 'ok' : 'FAIL');
}
await browser.close();
}
console.log(bad ? `${bad} failing checks` : 'all checks pass in chromium, firefox and webkit');
process.exitCode = bad ? 1 : 0; // a failing check must fail the run
A run with any check failing exits with status 1. Run in the Playwright 1.48.2 container, it prints (Chromium rows shown; Firefox and WebKit are checked against the same exact values and print a row only on failure):
chromium 320 width=320 left=0 pad=16 overflow=false ok
chromium 375 width=375 left=0 pad=16 overflow=false ok
chromium 767 width=767 left=0 pad=16 overflow=false ok
chromium 768 width=768 left=0 pad=32 overflow=false ok
chromium 1200 width=1200 left=0 pad=32 overflow=false ok
chromium 1440 width=1200 left=120 pad=32 overflow=false ok
chromium 1920 width=1200 left=360 pad=32 overflow=false ok
fluid 384 pad=16.00 ok
fluid 576 pad=24.00 ok
fluid 768 pad=32.00 ok
all checks pass in chromium, firefox and webkit
Hand check: at 1440 the leftover space is 1440 - 1200 = 240, so each side margin is 120. At 375 the content column is 375 - 2 x 16 = 343. At 576 the fluid padding is 4.1667 x 5.76 = 24.0px.
With DROP_BOX_SIZING=1 the run fails: at 375 the container is 407px wide (375 + 2 x 16) and the page scrolls sideways, at 1200 it is 1264px (1200 + 2 x 32). That failure is the reason the line exists.
Inside a flex or grid parent
The base rule keeps working inside a display: flex or display: grid parent only because of width: 100%. The cause differs by parent. In a flex row an item with width: auto shrink-wraps by default (the box is only as wide as what is inside it). In a flex column and in a grid, items with width: auto stretch to the parent by default, but an automatic margin switches that stretching off, so margin-inline: auto makes the container shrink-wrap there too; the automatic margins then centre the narrow box. The script puts the container with a short line of text inside four parents in a 1000px-wide viewport, with width: auto and with width: 100%:
import { chromium, firefox, webkit } from 'playwright';
const parents = { block: '', 'flex row': 'display:flex', 'flex column': 'display:flex;flex-direction:column', grid: 'display:grid' };
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const b = await type.launch(); const p = await b.newPage({ viewport: { width: 1000, height: 600 } });
for (const [pn, pcss] of Object.entries(parents)) {
for (const w of ['auto', '100%']) {
await p.setContent(`<style>body{margin:0}.container{box-sizing:border-box;width:${w};max-width:1200px;margin-inline:auto;padding-inline:16px}</style>
<div style="${pcss}"><div class="container" id="c">Short text</div></div>`);
const r = await p.evaluate(() => document.getElementById('c').getBoundingClientRect());
console.log(name.padEnd(8), pn.padEnd(12), `width:${w}`.padEnd(11), `width=${Math.round(r.width)} left=${Math.round(r.left)}`);
}
}
await b.close();
}
Chromium rows (Firefox and WebKit print 100 and 101px for the narrow case, because the text measures slightly differently):
chromium block width:auto width=1000 left=0
chromium block width:100% width=1000 left=0
chromium flex row width:auto width=95 left=453
chromium flex row width:100% width=1000 left=0
chromium flex column width:auto width=95 left=453
chromium flex column width:100% width=1000 left=0
chromium grid width:auto width=95 left=453
chromium grid width:100% width=1000 left=0
In a plain block parent width: auto already fills the parent (1000px). In the flex and grid parents the same rule collapses to the text width (about 95px here, centred at left=453) until width: 100% is added. Without margin-inline: auto, only the flex row still collapses; the flex column and grid parents then give 1000px. The 95px is an illustrative value that depends on the font.
Pitfalls
- Setting
width: 1200pxinstead ofmax-widthforces horizontal scrolling on any screen narrower than 1200px. - Using
margin: 0 autoand later adding vertical margins elsewhere resets them;margin-inline: autotouches only the horizontal axis. - A container inside a flex or grid parent shrinks to its content unless it has
width: 100%, as the widths above show; keep that line when copying the rule. - Do not stack nested
.containerelements: the paddings add up.
Running the code
mkdir container-demo && cd container-demo
echo '{"type":"module"}' > package.json
npm i playwright@1.48.2 # run inside mcr.microsoft.com/playwright:v1.48.2-jammy so the browsers exist
node container-check.mjs # add DROP_BOX_SIZING=1 to see it fail
node parents-check.mjs # the flex and grid parent comparison
Implement a responsive card grid using a mobile-first approach. Requirements:
- Mobile: single column
- Tablet: two columns
- Desktop: four columns
Provide the CSS (you may use CSS Grid or Flexbox). Explain your chosen breakpoints and why mobile-first helps maintain performance and progressive enhancement.
Sample Answer
Direct answer
Write the one-column layout as the base CSS, then add columns with min-width media queries: two columns from 600px and four from 1024px. Grid is the shortest tool for this (repeat(n, 1fr) per breakpoint); Flexbox gets the same result with percentage-based flex-basis values that must account for the gaps. A third version needs no media queries at all: repeat(auto-fit, minmax(min(100%, 15rem), 1fr)) lets the container width decide the column count.
Terms used below: a breakpoint is the viewport width at which a media query switches on; mobile-first means the unqualified CSS is the phone layout and min-width queries add to it; progressive enhancement means the baseline works everywhere and richer layout is layered on top; fr is a fraction of the free space after gaps.
The HTML and CSS
Four containers hold eight identical cards so the approaches can be compared side by side: grid with media queries (#grid), the same pattern with 2, 3 and 4 columns (#grid-234), Flexbox (#flex), and auto-fit (#auto). Two more containers hold two cards each to show auto-fit against auto-fill. The last element is a button. The CSS has three labelled rule sets, A (grid with media queries), B (Flexbox) and C (auto-fit), plus the button rule; the HTML is the same eight cards repeated once per container, so each container can be measured separately.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Responsive card grid</title>
<link rel="stylesheet" href="cards.css">
</head>
<body>
<section id="grid" class="grid" aria-label="Grid with media queries">
<article class="card"><h3>Card 1</h3></article>
<article class="card"><h3>Card 2</h3></article>
<article class="card"><h3>Card 3</h3></article>
<article class="card"><h3>Card 4</h3></article>
<article class="card"><h3>Card 5</h3></article>
<article class="card"><h3>Card 6</h3></article>
<article class="card"><h3>Card 7</h3></article>
<article class="card"><h3>Card 8</h3></article>
</section>
<section id="grid-234" class="grid grid--234" aria-label="Grid, 2 then 3 then 4 columns">
<article class="card"><h3>Card 1</h3></article>
<article class="card"><h3>Card 2</h3></article>
<article class="card"><h3>Card 3</h3></article>
<article class="card"><h3>Card 4</h3></article>
<article class="card"><h3>Card 5</h3></article>
<article class="card"><h3>Card 6</h3></article>
<article class="card"><h3>Card 7</h3></article>
<article class="card"><h3>Card 8</h3></article>
</section>
<section id="flex" class="flex" aria-label="Flexbox with media queries">
<article class="card"><h3>Card 1</h3></article>
<article class="card"><h3>Card 2</h3></article>
<article class="card"><h3>Card 3</h3></article>
<article class="card"><h3>Card 4</h3></article>
<article class="card"><h3>Card 5</h3></article>
<article class="card"><h3>Card 6</h3></article>
<article class="card"><h3>Card 7</h3></article>
<article class="card"><h3>Card 8</h3></article>
</section>
<section id="auto" class="auto" aria-label="auto-fit, no media queries">
<article class="card"><h3>Card 1</h3></article>
<article class="card"><h3>Card 2</h3></article>
<article class="card"><h3>Card 3</h3></article>
<article class="card"><h3>Card 4</h3></article>
<article class="card"><h3>Card 5</h3></article>
<article class="card"><h3>Card 6</h3></article>
<article class="card"><h3>Card 7</h3></article>
<article class="card"><h3>Card 8</h3></article>
</section>
<section id="few-fit" class="auto" aria-label="auto-fit, two cards">
<article class="card"><h3>Card 1</h3></article>
<article class="card"><h3>Card 2</h3></article>
</section>
<section id="few-fill" class="auto auto--fill" aria-label="auto-fill, two cards">
<article class="card"><h3>Card 1</h3></article>
<article class="card"><h3>Card 2</h3></article>
</section>
<button id="cta" class="btn" type="button">Get started</button>
</body>
</html>
* { box-sizing: border-box; }
:root { --gap: 16px; }
body { margin: 0; padding: 16px; font: 16px/1.5 system-ui, sans-serif; }
section { margin-bottom: 24px; }
.card { padding: 16px; background: #eef; border-radius: 8px; }
.card h3 { margin: 0; }
/* A. Grid, mobile-first: 1, then 2, then 4 columns. */
.grid { display: grid; grid-template-columns: 1fr; gap: var(--gap); }
@media (min-width: 600px) { .grid { grid-template-columns: repeat(2, 1fr); } }
@media (min-width: 1024px) { .grid { grid-template-columns: repeat(4, 1fr); } }
/* Same pattern with other numbers: 2, then 3, then 4 columns. */
.grid--234 { grid-template-columns: repeat(2, 1fr); }
@media (min-width: 768px) { .grid--234 { grid-template-columns: repeat(3, 1fr); } }
@media (min-width: 1024px) { .grid--234 { grid-template-columns: repeat(4, 1fr); } }
/* B. Flexbox: wrapping row; each item gets a width that leaves room for the gaps. */
.flex { display: flex; flex-wrap: wrap; gap: var(--gap); }
.flex > .card { flex: 0 0 100%; }
@media (min-width: 600px) { .flex > .card { flex-basis: calc((100% - var(--gap)) / 2); } }
@media (min-width: 1024px) { .flex > .card { flex-basis: calc((100% - 3 * var(--gap)) / 4); } }
/* C. No media queries: as many 15rem-minimum columns as fit. */
.auto { display: grid; gap: var(--gap);
grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr)); }
.auto--fill { grid-template-columns: repeat(auto-fill, minmax(min(100%, 15rem), 1fr)); }
/* Button: full width on small screens, natural width from 600px. */
.btn { display: block; width: 100%; padding: 12px 16px; font: inherit; }
@media (min-width: 600px) { .btn { display: inline-block; width: auto; } }
Choosing breakpoints
Breakpoints should sit where the content stops looking right, not at device names. Here the content rule is that each card should stay at 230px or wider (an illustrative minimum: enough for a card title and a short line of text without cramped wrapping; the arithmetic below works the same with any other minimum). With 16px of body padding on each side and 16px gaps, four columns hit exactly 230px when the viewport is 1000px: the container is 968px, so (968 - 3 x 16) / 4 = 230px. At 1024px the container is 992px and the cards are (992 - 3 x 16) / 4 = 236px. Two columns reach 230px from a 508px viewport ((476 - 16) / 2 = 230 with a 476px container), so 600px is a round number above that: (568 - 16) / 2 = 276px. The 1024px breakpoint is chosen the same way: it is a round number just above the 1000px at which four columns reach 230px. A 2, 3, 4 progression (#grid-234) is the same pattern with another middle step at 768px, where three columns give (736 - 2 x 16) / 3 = 234.7px.
Grid or Flexbox
| Question | Grid | Flexbox |
|---|---|---|
| Column count per breakpoint | repeat(2, 1fr): the intent is the code | flex-basis: calc((100% - 3 * var(--gap)) / 4): the gaps are your arithmetic |
| A partly filled last row | the last items sit in the same columns as the rows above | the last row's items sit on the same basis, left-aligned; use flex-grow and they stretch instead |
| Rows lined up in tracks | yes, columns are shared by every row | each row is laid out on its own |
| Unknown number of items per row | auto-fill / auto-fit | only through flex-wrap with a fixed basis |
Grid is the better default for a card grid because the container, not the cards, owns the column structure. Flexbox is still right when the items are a single row of mixed sizes (a toolbar, a tag list), which is a different shape of layout.
No media queries: auto-fit with minmax
repeat(auto-fit, minmax(min(100%, 15rem), 1fr)) means: make as many columns as fit, each at least 15rem (240px at the default font size) and sharing leftover space equally. The min(100%, 15rem) stops a narrow container from forcing a 15rem column wider than itself. With a 16px gap the number of columns is the largest n with n x 240 + (n - 1) x 16 not above the container width, which gives 1, 2, 3 and 4 at containers of 343, 736, 992 and 1248px (viewports 375, 768, 1024 and 1280). Traced at the 768px viewport, whose container is 736px: one column needs 240px, two need 2 x 240 + 16 = 496px, three need 3 x 240 + 2 x 16 = 752px, which is more than 736px, so the largest n that fits is 2; the two columns then share the leftover space equally, (736 - 16) / 2 = 360px each, the 360.0px in the output. The run below confirms that, including the case the media-query version cannot express: at 1024px auto-fit gives 3 columns, not 4.
auto-fit and auto-fill differ when there are fewer items than columns. MDN: auto-fit "behaves the same as auto-fill, except that after placing the grid items any empty repeated tracks are collapsed." With two cards at 1280px the auto-fit cards stretch to fill the row (616px each) while auto-fill keeps the empty tracks and the cards stay 300px.
The button
.btn is display: block; width: 100% by default and display: inline-block; width: auto from 600px. The default is what a narrow screen wants (a full-width tap target) and the query restores the natural size.
Verifying in three engines
The script counts distinct left edges among each container's cards to get the real column count, and reads card and button widths. Every expectation is also derived by hand above: 768px gives (736 - 16) / 2 = 360px for two columns, and 1280px gives (1248 - 3 x 16) / 4 = 300px for four.
import { chromium, firefox, webkit } from 'playwright';
import { pathToFileURL } from 'node:url';
import path from 'node:path';
const url = pathToFileURL(path.resolve('index.html')).href;
const near = (a, b) => Math.abs(a - b) <= 0.5;
let failures = 0;
const expect = (ok, msg) => { if (!ok) { failures++; console.log(' FAIL', msg); } };
// Columns = number of distinct left edges among a container's cards.
const columns = (sel) => {
const cards = [...document.querySelectorAll(sel + ' .card')];
const lefts = new Set(cards.map((c) => Math.round(c.getBoundingClientRect().left)));
return { cols: lefts.size, width: cards[0].getBoundingClientRect().width };
};
const buttonWidth = () => document.querySelector('#cta').getBoundingClientRect().width;
const want = { // width -> expected columns for each container
375: { '#grid': 1, '#grid-234': 2, '#flex': 1, '#auto': 1 },
768: { '#grid': 2, '#grid-234': 3, '#flex': 2, '#auto': 2 },
1024: { '#grid': 4, '#grid-234': 4, '#flex': 4, '#auto': 3 },
1280: { '#grid': 4, '#grid-234': 4, '#flex': 4, '#auto': 4 },
};
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
for (const width of Object.keys(want).map(Number)) {
const page = await browser.newPage({ viewport: { width, height: 800 } });
await page.goto(url);
const row = [];
for (const [sel, n] of Object.entries(want[width])) {
const got = await page.evaluate(columns, sel);
expect(got.cols === n, `${name} ${width} ${sel}: expected ${n} columns, got ${got.cols}`);
row.push(`${sel}=${got.cols} cols @ ${got.width.toFixed(1)}px`);
}
const bw = await page.evaluate(buttonWidth);
expect(width < 600 ? near(bw, width - 32) : bw < 200, `${name} ${width}: button width ${bw}`);
if (name === 'chromium') console.log(width, row.join(' | '), '| button', bw.toFixed(1) + 'px');
if (width === 1280) {
const fit = await page.evaluate(columns, '#few-fit');
const fill = await page.evaluate(columns, '#few-fill');
expect(fit.width > 2 * fill.width, `${name}: auto-fit stretches 2 cards, auto-fill keeps empty tracks`);
if (name === 'chromium') console.log('2 cards at 1280: auto-fit', fit.width, 'px each, auto-fill', fill.width, 'px each');
}
await page.close();
}
await browser.close();
}
console.log(failures === 0 ? 'ALL CHECKS PASSED' : `${failures} CHECK(S) FAILED`);
process.exit(failures ? 1 : 0);
Output (Chromium lines printed; Firefox and WebKit are asserted against the same expectations):
375 #grid=1 cols @ 343.0px | #grid-234=2 cols @ 163.5px | #flex=1 cols @ 343.0px | #auto=1 cols @ 343.0px | button 343.0px
768 #grid=2 cols @ 360.0px | #grid-234=3 cols @ 234.7px | #flex=2 cols @ 360.0px | #auto=2 cols @ 360.0px | button 114.6px
1024 #grid=4 cols @ 236.0px | #grid-234=4 cols @ 236.0px | #flex=4 cols @ 236.0px | #auto=3 cols @ 320.0px | button 114.6px
1280 #grid=4 cols @ 300.0px | #grid-234=4 cols @ 300.0px | #flex=4 cols @ 300.0px | #auto=4 cols @ 300.0px | button 114.6px
2 cards at 1280: auto-fit 616 px each, auto-fill 300 px each
ALL CHECKS PASSED
Removing the min-width: 1024px grid rule from the stylesheet and re-running makes the script fail at 1024 and 1280 in all three engines, so the check exercises the rule it describes. Chromium's lines:
FAIL chromium 1024 #grid: expected 4 columns, got 2
FAIL chromium 1280 #grid: expected 4 columns, got 2
The last line of that run reads 6 CHECK(S) FAILED. WebKit here is Playwright's build, not Safari on iOS.
Why mobile-first helps
- Progressive enhancement. The unqualified rules are the whole layout for any browser that does not apply the queries, and the narrow layout is the simplest one, so nothing needs undoing.
- Less overriding. Each breakpoint only adds columns, so rules do not have to cancel each other. Media queries add no specificity of their own, so a later rule at the same specificity wins by source order, and
min-widthqueries ordered from small to large read as a single escalating sequence. - Performance, stated precisely. A mobile-first file is not smaller by itself, and web.dev notes that "The browser downloads all CSS resources, regardless of blocking or non-blocking behavior." The measurable lever is splitting wide-screen CSS into a
<link rel="stylesheet" href="wide.css" media="(min-width: 1024px)">. A stylesheet is render-blocking when the browser will not paint anything until it has downloaded and parsed it (first paint is the moment the first pixels of the page appear). web.dev says a stylesheet whose media query does not match the current device is non-render-blocking, and the browser fetches it at lower priority, so a phone does not wait for the wide-screen rules.
Trade-offs and pitfalls
- Flexbox percentage maths: forgetting the gap in
flex-basismakes the fourth card wrap onto a new row. Prefercalc((100% - 3 * var(--gap)) / 4). 1frhas an automatic minimum.1frbehaves likeminmax(auto, 1fr), and theautominimum is the item's smallest possible width, itsmin-contentsize (the width of its longest unbreakable word or string). A card containing an unbreakable string therefore widens its track instead of shrinking; useminmax(0, 1fr)if cards hold long unbroken content.auto-fitcannot guarantee exactly four columns. If design demands exactly 1, 2, 4, use explicit queries.- Edge cases: eight cards fill 4 columns twice, but seven would leave a partly filled last row in every version above; an empty container renders nothing; zoomed text (larger rem) reduces the column count in the
auto-fitversion because the 15rem minimum grows.
Running the code
mkdir demo && cd demo # put index.html, cards.css, check.mjs here
npm init -y && npm pkg set type=module
npm i playwright@1.48.2 && npx playwright install chromium firefox webkit
node check.mjs
You are reviewing a component library and find three recurring accessibility problems: clickable divs, icon-only buttons with no text, and focus that disappears when a panel opens. For each, show the markup fix and explain what a keyboard or screen-reader user experiences before and after.
Sample Answer
Direct answer
All three problems have a markup-level fix, and the fixes are small. Clickable divs become <button type="button">, so the browser supplies the role, the Tab stop and the Enter and Space keys. Icon-only buttons get an accessible name (the label that assistive technology and the browser's accessibility tree expose for a control) from aria-label or from visually hidden text, with the decorative icon marked aria-hidden="true". A panel that takes focus from the page becomes a <dialog> opened with showModal(), which moves focus into the panel, makes the rest of the page inert so that Tab and Shift+Tab cannot land on anything behind the panel (inert: the browser ignores clicks and focus there and hides it from assistive technology), closes on Escape and, in the engines tested below, hands focus back to the trigger. All of it is visible to a keyboard user only if a :focus-visible outline replaces the library's outline: none reset.
The three problems, side by side
| Problem | Before (what the user gets) | Markup fix | After (what the user gets) |
|---|---|---|---|
| Clickable div | Tab skips it; Enter and Space do nothing; no role is set on it, so it is not a button | <button type="button">Save</button> | Tab reaches it; Enter and Space each click it once |
| Icon-only button | The accessibility tree holds a button whose name is the empty string, so the control has no name | aria-label="Close" on the button plus aria-hidden="true" on the <svg>, or <span class="visually-hidden">Search</span> | The tree holds buttons named "Close" and "Search" |
| Panel steals focus | The open trigger is hidden while focused, document.activeElement falls to <body>, and the next Tab lands somewhere the user did not choose | <dialog> and one showModal() call | Focus moves into the dialog, six Tab presses never reach the page behind, Escape closes it and focus is back on the trigger |
Fix 1: clickable divs
A div has no role and no tab stop. tabindex="0" and role="button" plus key handlers can imitate a button, but a native <button> does the same with no script, so in a library the right fix is to render a <button> and keep the old class for the look. Add type="button" so it does not submit an enclosing form by accident. Before and after for a keyboard user: in the test, three Tab presses visit the icon button, the open button and the repaired Save button, and never the div; Enter and Space on the repaired button give 2 clicks while the same keys aimed at the div give 0. That zero is only meaningful if the check can fail, so a mutation swaps the div for a <button> with the same id and expects 2 clicks, which the run shows (divAsButtonClicks: 2).
Fix 2: icon-only buttons
What the user gets: a screen reader builds what it says from the control's role and name. The unfixed icon button has the role button and an empty name, so there is a control to reach but nothing that says what it does; MDN describes aria-label on an icon-only button as essential for screen reader users to understand its function ("Close" in its example). The clickable div has no role, only its text content, so it reads like plain text and not as something to activate. After the fixes the buttons carry the names "Close" and "Search" and the role button, and the repaired Save is a button named "Save". The exact spoken wording differs between screen readers.
An <svg> with no text contributes no name, and a button's name is computed from its content, so the button is exposed with an empty name. Two fixes work, and both are exercised:
aria-label="Close"on the<button>: the name is exactly the string you give it. Mark the inner iconaria-hidden="true"(which hides it from assistive technology) andfocusable="false"(which keeps the SVG itself from becoming a Tab stop where a browser would make it one) so it is not double-counted.- Visually hidden text: a
<span class="visually-hidden">Search</span>inside the button. The CSS reads as follows:position: absolutetakes the span out of the layout so it takes no space;widthandheightof 1px shrink its box;overflow: hiddenandclip-path: inset(50%)(a clip that cuts 50% from every side, leaving nothing visible) hide anything beyond that;white-space: nowrapkeeps the text on one line so it is not wrapped into a tall column. The test reads the box as 1x1, so the text is invisible but still in the accessibility tree.
Fix 3: focus that vanishes when a panel opens
The faulty library code hides the trigger and shows the panel without moving focus. Focus sits on an element that is now display: none, so document.activeElement reverts to <body> and the keyboard user loses their place. Where the next Tab goes then depends on the engine (in the run below Chromium and Firefox continue from the old position, to the panel's button, and WebKit starts from the top of the page).
The fix is markup plus one line of script: the browser feature does the focus management, so do not hand-roll a focus trap. Walking the unfixed panel with the Tab key shows the failure: the first Tab reaches the icon button, the second reaches "Open filters", Enter hides that button and shows the panel, and focus drops to <body>. The next Tab then goes to the panel's Done button (b-close) in Chromium and Firefox, or back to the first icon button in WebKit, and a keyboard user who expected to start inside the panel has to find it. The clickable div is never visited at all.
<dialog id="a-panel" aria-labelledby="a-title"> ... </dialog>
<script>document.getElementById('a-open').addEventListener('click', () => document.getElementById('a-panel').showModal());</script>
MDN documents the pieces (inert means the browser ignores clicks and focus on that part of the page and hides it from assistive technology): "Modal dialog boxes block interaction with other UI elements, making the rest of the page inert", "By default, a dialog invoked by the showModal() method can be dismissed by pressing the Esc key", and "focus is set on the first nested focusable element" (use autofocus to choose a better target). In the run, the first focusable element in the dialog was the checkbox, since it comes first in the source. That is also the reason to put the heading and controls in a deliberate order. The run also shows focus returning to the opener after Escape in all three engines.
Focus style for all three
The library's button:focus { outline: none; } reset is why users cannot see focus, and replacing it is part of every fix above. The test replaces it with :is(button, a, input):focus-visible { outline: 3px solid ...; } (:is() matches an element that matches any selector in its list; :focus-visible matches when the browser decides an indicator is useful, such as for keyboard focus) and checks that the computed outline after Tab is 3px solid; with the rule deleted it is none.
The page and the test
<!-- library.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Component library fixes</title>
<style>
button:focus, [role="button"]:focus { outline: none; } /* the library's reset */
:is(button, a, input):focus-visible { outline: 3px solid #f59e0b; outline-offset: 2px; }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.icon { width: 1.25rem; height: 1.25rem; }
</style>
</head>
<body>
<h1>Before</h1>
<div id="b-div" class="action">Save</div>
<button id="b-icon" type="button"><svg class="icon" viewBox="0 0 20 20"><path d="M4 4l12 12M16 4L4 16" stroke="currentColor" fill="none"/></svg></button>
<button id="b-open" type="button">Open filters</button>
<div id="b-panel" hidden><h2>Filters</h2><button id="b-close" type="button">Done</button></div>
<h1>After</h1>
<button id="a-btn" type="button">Save</button>
<button id="a-label" type="button" aria-label="Close"><svg class="icon" viewBox="0 0 20 20" aria-hidden="true" focusable="false"><path d="M4 4l12 12M16 4L4 16" stroke="currentColor" fill="none"/></svg></button>
<button id="a-text" type="button"><svg class="icon" viewBox="0 0 20 20" aria-hidden="true" focusable="false"><circle cx="8" cy="8" r="5" stroke="currentColor" fill="none"/></svg><span class="visually-hidden">Search</span></button>
<button id="a-open" type="button">Open filters</button>
<dialog id="a-panel" aria-labelledby="a-title">
<h2 id="a-title">Filters</h2>
<label><input id="a-stock" type="checkbox"> In stock only</label>
<button id="a-done" type="button" aria-label="Close filters"><svg class="icon" viewBox="0 0 20 20" aria-hidden="true" focusable="false"><path d="M4 4l12 12M16 4L4 16" stroke="currentColor" fill="none"/></svg></button>
</dialog>
<p><a id="bg" href="#end">Link behind the panel</a></p>
<span id="end"></span>
<script>
window.n = { bDiv: 0, aBtn: 0 };
document.getElementById('b-div').addEventListener('click', () => window.n.bDiv++);
document.getElementById('a-btn').addEventListener('click', () => window.n.aBtn++);
// Before: the trigger is hidden and the panel shown, and focus is not moved anywhere.
document.getElementById('b-open').addEventListener('click', () => {
document.getElementById('b-open').hidden = true;
document.getElementById('b-panel').hidden = false;
});
// After: showModal() is the one line of JS; focus, an inert page behind the panel, Escape and focus return come from <dialog>.
document.getElementById('a-open').addEventListener('click', () => document.getElementById('a-panel').showModal());
document.getElementById('a-done').addEventListener('click', () => document.getElementById('a-panel').close());
</script>
</body>
</html>
The test runs in Chromium, Firefox and WebKit (Playwright's WebKit build; this is not Safari). It asserts the Tab stops, the click counts, the accessible names read from the accessibility tree (exactly one empty name, which is the unfixed icon button, plus "Close" and "Search"), the visually hidden box size, where focus goes before and after, that six Tab presses never reach the link behind the dialog, that Escape returns focus to the opener, and the outline. Three mutations (deliberately changing the markup to prove a check can fail) show the checks do work: replacing the div with a <button> makes the div check see 2 clicks instead of 0, deleting aria-label="Close" makes a second empty name appear (the string occurs once, because the dialog's button says Close filters; the test throws if that stops being true), and deleting the focus rule gives outline none.
// library-test.mjs
import { chromium, firefox, webkit } from 'playwright';
import { readFileSync } from 'node:fs';
const html = readFileSync('library.html', 'utf8');
let failures = 0;
const check = (ok, msg) => { if (!ok) { failures++; console.log(' FAIL', msg); } };
const active = (page) => page.evaluate(() => document.activeElement.id || document.activeElement.tagName);
// Accessible name of every button in the accessibility tree, in document order.
const buttons = async (page) => {
const out = [];
(function walk(n) { if (n.role === 'button') out.push(n.name); (n.children || []).forEach(walk); })(await page.accessibility.snapshot({ interestingOnly: false }));
return out;
};
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const b = await type.launch();
const page = await b.newPage();
await page.setContent(html);
const result = {};
// 1. Clickable div versus button: keyboard reach and activation.
const tabStops = [];
for (let i = 0; i < 3; i++) { await page.keyboard.press('Tab'); tabStops.push(await active(page)); }
result.tabStops = tabStops.join('>');
check(!tabStops.includes('b-div') && tabStops[0] === 'b-icon', `${name} tab stops ${result.tabStops}`);
await page.focus('#a-btn');
await page.keyboard.press('Enter'); await page.keyboard.press(' ');
result.buttonClicks = await page.evaluate(() => window.n.aBtn);
// Try the same two keys on the div: blur whatever has focus, ask for focus on the div, press Enter and Space.
const divKeyboardClicks = async () => {
await page.evaluate(() => document.activeElement.blur());
await page.focus('#b-div');
await page.keyboard.press('Enter'); await page.keyboard.press(' ');
return page.evaluate(() => window.n.bDiv);
};
result.divClicks = await divKeyboardClicks();
check(result.buttonClicks === 2 && result.divClicks === 0, `${name} clicks`);
// 2. Icon-only buttons: names in the accessibility tree.
const names = await buttons(page);
result.names = JSON.stringify(names);
check(names.filter((n) => n === '').length === 1 && names.includes('Close') && names.includes('Search') && names.length === 6, `${name} names ${result.names}`);
const hidden = await page.$eval('#a-text .visually-hidden', (el) => { const r = el.getBoundingClientRect(); return `${r.width}x${r.height}`; });
result.visuallyHiddenBox = hidden;
check(hidden === '1x1', `${name} visually-hidden box ${hidden}`);
// 3a. Before: the trigger is hidden while it holds focus, so focus falls back to the body (where the next Tab goes is engine-dependent).
await page.focus('#b-open'); await page.keyboard.press('Enter');
// WebKit reports the hidden trigger as focused for one frame, so wait for focus to settle on the body.
await page.waitForFunction(() => document.activeElement === document.body);
result.beforeFocus = await active(page);
await page.keyboard.press('Tab');
result.tabAfterLoss = await active(page);
check(result.beforeFocus === 'BODY', `${name} before focus ${result.beforeFocus}`);
// 3b. After: showModal moves focus into the dialog, makes the page behind it unreachable by Tab, Escape closes it and returns focus to the trigger.
await page.focus('#a-open'); await page.keyboard.press('Enter');
result.afterFocus = await active(page);
check(await page.evaluate(() => !!document.activeElement.closest('dialog')), `${name} focus not in dialog`);
let leaked = false;
for (let i = 0; i < 6; i++) { await page.keyboard.press('Tab'); if (await active(page) === 'bg') leaked = true; }
result.tabLeaksToBackground = leaked;
check(!leaked, `${name} Tab reached background link`);
await page.keyboard.press('Escape');
await page.waitForFunction(() => !document.getElementById('a-panel').open);
result.afterEscape = await active(page);
check(result.afterEscape === 'a-open', `${name} focus after Escape ${result.afterEscape}`);
// 4. Focus indicator: visible on keyboard focus, from the :focus-visible rule.
await page.focus('#a-open'); await page.keyboard.press('Shift+Tab'); await page.keyboard.press('Tab');
result.outline = await page.$eval('#a-open', (el) => getComputedStyle(el).outlineWidth + ' ' + getComputedStyle(el).outlineStyle);
check(result.outline === '3px solid', `${name} outline ${result.outline}`);
// 5. Mutations: delete aria-label (name goes empty); delete the :focus-visible rule (outline goes none).
const noLabel = html.replace(' aria-label="Close"', '');
if (html.split(' aria-label="Close"').length !== 2) throw new Error('aria-label="Close" is not unique');
await page.setContent(noLabel);
const mutNames = await buttons(page);
check(mutNames.filter((n) => n === '').length === 2, `${name} mutation names ${JSON.stringify(mutNames)}`);
const noRule = html.replace(/ :is\(button[^\n]*\n/, '');
if (noRule === html) throw new Error('focus rule not removed');
// Mutation: make the div a real button (same id, so the same counter) and the div check must now see 2 clicks.
await page.setContent(html.replace('<div id="b-div" class="action">Save</div>', '<button id="b-div" type="button">Save</button>'));
const mutDivClicks = await divKeyboardClicks();
check(mutDivClicks === 2, `${name} mutation div-as-button should give 2 clicks, got ${mutDivClicks}`);
result.divAsButtonClicks = mutDivClicks;
await page.setContent(noRule);
await page.focus('#a-open'); await page.keyboard.press('Shift+Tab'); await page.keyboard.press('Tab');
result.outlineWithoutRule = await page.$eval('#a-open', (el) => getComputedStyle(el).outlineStyle);
check(result.outlineWithoutRule === 'none', `${name} mutation outline`);
console.log(name, JSON.stringify(result));
await b.close();
}
console.log(failures === 0 ? 'ALL CHECKS PASSED' : `${failures} FAILURES`);
process.exit(failures ? 1 : 0);
Output (the script above run in the Playwright 1.48.2 image; the lines were identical across repeated runs). The keys are the measurements: tabStops is where three Tab presses land, names is the name of every button in the accessibility tree (the single "" is the unfixed icon button), beforeFocus and tabAfterLoss are the focus owner after the unfixed panel opens and after one more Tab, afterFocus is where showModal() puts focus, and afterEscape is where focus returns:
chromium {"tabStops":"b-icon>b-open>a-btn","buttonClicks":2,"divClicks":0,"names":"[\"\",\"Open filters\",\"Save\",\"Close\",\"Search\",\"Open filters\"]","visuallyHiddenBox":"1x1","beforeFocus":"BODY","tabAfterLoss":"b-close","afterFocus":"a-stock","tabLeaksToBackground":false,"afterEscape":"a-open","outline":"3px solid","divAsButtonClicks":2,"outlineWithoutRule":"none"}
firefox {"tabStops":"b-icon>b-open>a-btn","buttonClicks":2,"divClicks":0,"names":"[\"\",\"Open filters\",\"Save\",\"Close\",\"Search\",\"Open filters\"]","visuallyHiddenBox":"1x1","beforeFocus":"BODY","tabAfterLoss":"b-close","afterFocus":"a-stock","tabLeaksToBackground":false,"afterEscape":"a-open","outline":"3px solid","divAsButtonClicks":2,"outlineWithoutRule":"none"}
webkit {"tabStops":"b-icon>b-open>a-btn","buttonClicks":2,"divClicks":0,"names":"[\"\",\"Open filters\",\"Save\",\"Close\",\"Search\",\"Open filters\"]","visuallyHiddenBox":"1x1","beforeFocus":"BODY","tabAfterLoss":"b-icon","afterFocus":"a-stock","tabLeaksToBackground":false,"afterEscape":"a-open","outline":"3px solid","divAsButtonClicks":2,"outlineWithoutRule":"none"}
ALL CHECKS PASSED
Trade-offs and pitfalls
aria-labelreplaces visible text. Put it on controls with no visible text. On a button that already shows "Close",aria-labeladds a second source of text that can drift from the visible words; use it for icon-only controls.- A
<dialog>is the markup answer, not the whole component. The JavaScript step is just theshowModal()call and, if the app removes or re-renders the trigger, restoring focus to a sensible element yourself, since focus return is only helpful when the opener still exists. Widget-level focus management belongs to the component's own code. - Native
<dialog>is not a closed loop. The specification only makes the rest of the document inert, so the dialog's controls are the only page content Tab can reach, but the browser's own interface (address bar, toolbar) sits outside the document. In a normal window, Tab past the last control can move focus there instead of wrapping to the first control; the W3C ARIA Authoring Practices discussion of this (w3c/aria-practices issue 1772) records that native dialogs do not wrap. The headless browsers used in the test have no such interface, so the test can show only that the page behind is unreachable (six Tab presses never reach the link), not that focus cycles. Do not claim a closed loop unless you have written one and tested it in a headed browser. - Do not suppress the Escape default with a key handler that swallows it, or keyboard users lose the way out.
- Library rollout. Fix these three in the shared component so every consumer inherits the repair, and add the Playwright checks above to the component's test suite so a change that removes a label or reintroduces
outline: nonefails.
Running the code
mkdir demo && cd demo && echo '{"type":"module"}' > package.json
# save library.html and library-test.mjs from above into this folder
docker run --rm -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c 'npm i playwright@1.48.2 && node library-test.mjs'
When should you use a <button> element versus an <a href='...'> anchor or <input type='button'>? Discuss semantic intent, default keyboard and screen-reader behavior, focusability, and how incorrect choices can harm accessibility. Provide examples of correct and incorrect usage for navigation, actions, and form submission.
Sample Answer
Direct answer
Choose by what the control does. If activating it goes somewhere (a different URL, a section of the page), it is a link: <a href="...">. If it does something on the current page (opens a dialog, toggles a panel, saves, deletes), it is a <button type="button">. If it submits a form, it is a <button type="submit"> (or <input type="submit">) inside the <form>. <input type="button"> is an older equivalent of a plain button whose label comes from its value attribute and which cannot contain markup; prefer <button>.
Terms: semantic intent is the meaning the element's tag tells the browser and assistive technology (screen readers and similar tools); the role is how that meaning is exposed to them (button, link); an element is focusable if the Tab key can land on it; the accessibility tree is the browser's parallel version of the page that assistive technology reads; the accessible name is the label that tree gives the control.
What each element gives you for free
<button> | <input type="button"> | <a href> | <div role="button"> | |
|---|---|---|---|---|
| Role exposed | button | button | link | button (only if you add the role) |
| In the Tab order | yes | yes | yes | no, unless you add tabindex |
| Enter activates | yes | yes | yes | no |
| Space activates | yes | yes | no (Space scrolls the page) | no |
| Accessible name from | its content | its value | its content | its content |
| Submits a form | yes, by default (see below) | no (type="submit" is a separate input type) | no | no |
The role, Tab, Enter, Space and form-submit rows are measured in the run below, identical in Chromium, Firefox and WebKit. The roles come from Chromium's accessibility tree, which is what assistive technology reads from the browser; it is not a screen reader, and the WebKit used here is Playwright's build, not Safari on iOS.
What the standards and MDN say
- MDN on
role="button"(an ARIA attribute that sets the role by hand): it "tells assistive technology that the element is a button, but does not provide other typical button functionality such as click events and keyboard handling." It adds that you "should generally use<button>or<input>withtype="button"instead", and that a non-focusable element given the role needstabindex, plus "event handlers forclickandkeydownevents" that handle Enter and Space. - MDN on a link used as a button: "adding
role="button"alone is not sufficient", because a key handler for Space is also needed to match native buttons. - HTML-AAM (the specification for how HTML maps to the accessibility tree) maps
<a>with anhrefto thelinkrole. - MDN on
<button>:submit"is the default if the attribute is not specified for buttons associated with a<form>". It warns: "If your buttons are not for submitting form data to a server, be sure to set theirtypeattribute tobutton."
Correct and incorrect usage
Navigation
<!-- correct: a real URL, so open-in-new-tab, copy-link and the URL preview all work -->
<a href="/pricing">Pricing</a>
<!-- incorrect: navigation hidden in a handler on a button; no URL for the browser to offer -->
<button onclick="location.href='/pricing'">Pricing</button>
Actions on the current page
<!-- correct: focusable, Enter and Space work, role is button -->
<button type="button" aria-expanded="false" aria-controls="filters">Filters</button>
<!-- aria-expanded tells assistive technology whether the panel is open; aria-controls names the panel's id, here filters -->
<!-- incorrect: announced as a link, Space does not activate it, and href="#" jumps to the top -->
<a href="#" onclick="toggleFilters()">Filters</a>
<!-- incorrect: not in the Tab order and no keyboard activation -->
<div role="button" onclick="toggleFilters()">Filters</div>
Form submission
<!-- correct: submit is the default type for a button in a form, but say it -->
<form action="/search"><input name="q" aria-label="Search"><button type="submit">Search</button></form>
<!-- incorrect: a plain button inside the form will submit it unexpectedly; mark non-submit buttons type="button" -->
<form action="/search"><input name="q" aria-label="Search"><button>Clear filters</button></form>
<!-- incorrect: a link or div cannot submit the form -->
<a href="#" id="go">Search</a>
Measuring it
The page puts a default <button>, a type="button" button, an <input type="button">, a link, an <a> without href, a div with role="button" and a div with role="button" tabindex="0" in one form, counts the click events produced by Tab, Enter and Space, and counts submit events. The Space-on-link scrolling check waits up to 500ms for the page to move, so it does not depend on timing luck, and the page is scrolled back to the top between Enter and Space, so a scroll caused by Enter (a link to #details scrolls to that element) is not mistaken for a scroll caused by Space. Step by step, the script: puts all seven controls in a form; adds a click counter to every control and a submit counter to the form (Object.fromEntries builds the {id: 0} table of counters); presses Tab five times and records which element has focus each time; then, for each control, focuses it, presses Enter and reads its click count, scrolls to the top, presses Space and reads the count again, and finally checks whether the page scrolled. The difference between counts is how many clicks that key produced.
import { chromium, firefox, webkit } from 'playwright';
import assert from 'node:assert/strict';
const html = `
<form id="f" action="#submitted">
<button id="save">Save</button>
<button id="plain" type="button">Plain</button>
<input id="field-btn" type="button" value="Input button">
<a id="link" href="#details">Details</a>
<a id="fake-link">Anchor without href</a>
<div id="div-btn" role="button">Div role=button</div>
<div id="div-btn-tab" role="button" tabindex="0">Div with tabindex only</div>
</form>
<div id="details" style="margin-top:2000px">Details</div>`;
const ids = ['save', 'plain', 'field-btn', 'link', 'fake-link', 'div-btn', 'div-btn-tab'];
const runIn = async (type) => {
const browser = await type.launch();
const page = await browser.newPage();
await page.setContent(html);
await page.evaluate((ids) => {
window.clicks = Object.fromEntries(ids.map((i) => [i, 0]));
window.submits = 0;
for (const id of ids) document.getElementById(id).addEventListener('click', () => window.clicks[id]++);
document.getElementById('f').addEventListener('submit', (e) => { window.submits++; e.preventDefault(); });
}, ids);
const tabOrder = []; // which elements does Tab reach?
for (let i = 0; i < 5; i++) {
await page.keyboard.press('Tab');
tabOrder.push(await page.evaluate(() => document.activeElement.id));
}
const rows = {}; // does Enter / Space activate each one?
for (const id of ids) {
await page.evaluate((id) => { document.getElementById(id).focus(); window.scrollTo(0, 0); }, id);
const focusable = (await page.evaluate(() => document.activeElement.id)) === id;
const n = () => page.evaluate((id) => window.clicks[id], id);
const c0 = await n();
await page.keyboard.press('Enter');
const c1 = await n();
await page.evaluate(() => window.scrollTo(0, 0)); // undo any scroll Enter caused, so only Space is measured below
await page.keyboard.press('Space');
const c2 = await n();
rows[id] = { focusable, enter: c1 - c0, space: c2 - c1, spaceScrollsPage: await page.waitForFunction(() => window.scrollY > 0, null, { timeout: 500 }).then(() => true, () => false) };
}
const submits = await page.evaluate(() => window.submits);
let roles = null;
if (type === chromium) { // Chromium's accessibility tree, not a screen reader
roles = [];
(function walk(n) {
if (n.role !== 'text' && /^(Save|Plain|Input button|Details|Div)/.test(n.name || '')) roles.push(`${n.role}: ${n.name}`);
(n.children || []).forEach(walk);
})(await page.accessibility.snapshot({ interestingOnly: false }));
}
await browser.close();
return { tabOrder, rows, submits, roles };
};
const results = {};
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) results[name] = await runIn(type);
const { roles, ...chromiumResult } = results.chromium;
for (const name of ['firefox', 'webkit']) {
const { roles: _ignored, ...other } = results[name];
assert.deepEqual(other, chromiumResult, `${name} differs from chromium`);
}
console.log('Identical in chromium, firefox and webkit.');
console.log('Tab order:', chromiumResult.tabOrder.join(' > '));
console.table(chromiumResult.rows);
console.log('submit events from the form (Enter + Space on each control):', chromiumResult.submits);
console.log('Chromium accessibility tree:', roles.join(' | '));
Output:
Identical in chromium, firefox and webkit.
Tab order: save > plain > field-btn > link > div-btn-tab
┌─────────────┬───────────┬───────┬───────┬──────────────────┐
│ (index) │ focusable │ enter │ space │ spaceScrollsPage │
├─────────────┼───────────┼───────┼───────┼──────────────────┤
│ save │ true │ 1 │ 1 │ false │
│ plain │ true │ 1 │ 1 │ false │
│ field-btn │ true │ 1 │ 1 │ false │
│ link │ true │ 1 │ 0 │ true │
│ fake-link │ false │ 0 │ 0 │ true │
│ div-btn │ false │ 0 │ 0 │ true │
│ div-btn-tab │ true │ 0 │ 0 │ true │
└─────────────┴───────────┴───────┴───────┴──────────────────┘
submit events from the form (Enter + Space on each control): 2
Chromium accessibility tree: button: Save | button: Plain | button: Input button | link: Details | button: Div role=button | button: Div with tabindex only
Reading it: focusable says the element took focus when asked; enter and space are the click events each key produced; spaceScrollsPage is true when pressing Space moved the page, which happens when the focused element does not consume Space (the browser's default for Space on a page is to scroll down). The form received 2 submit events in total, which matches the default <button> being activated twice (Enter, then Space); the type="button" button and the <input type="button"> are activated too but are not submit controls. The link responds to Enter but not Space, and Space scrolls the page instead. An <a> with no href is not focusable at all. The div with the role alone is invisible to the keyboard, and adding tabindex="0" makes it reachable but still gives it no Enter or Space behaviour. spaceScrollsPage is true for the link and for the three non-button rows because none of them consumes Space; the button rows are false because the button handles Space itself, so the page stays put.
Trade-offs and pitfalls
href="#"plus a click handler is the most common wrong choice: the element is announced as a link and the browser scrolls to the top unless the handler cancels the link's default action (callsevent.preventDefault(), which tells the browser not to do what it would normally do for that event, here following the link).- A button that navigates is wrong, but so is a link used as a toggle. A single-page app's client-side navigation should still render real
<a href>elements whose click handler routes without a reload. - Always set
type. A<button>with no type inside a form submits it; MDN flags the "possibly destroying the current state of the document" consequence. - Styling is not a reason to choose. A link styled as a button and a button styled as a link both look right and behave wrong; style the element that has the right semantics.
- Icon-only buttons need a name: give them text, visually hidden text, or
aria-label. - Edge cases: an
<a>withouthrefis not focusable at all (measured above), so a placeholder anchor is invisible to the keyboard; and native controls give you the keyboard and role behaviour, but the visible focus style is still yours to keep (do not remove the outline).
Running the code
mkdir demo && cd demo # put check.mjs here
npm init -y && npm pkg set type=module
npm i playwright@1.48.2 && npx playwright install chromium firefox webkit
node check.mjs
Unlock Full Question Bank
Get access to all 26 Frontend Fundamentals: HTML, CSS, and Responsive Styling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.