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.
Design accessible focus and hover styles for interactive controls. Requirements:
- Keep visible focus outlines for keyboard users
- Avoid relying only on :hover for critical functionality (touch devices)
- Use :focus-visible where appropriate
Provide CSS snippets that implement a consistent focus treatment and explain how to prevent hover-only styles from degrading touch experiences.
Sample Answer
Direct answer
Keep one focus rule for the whole page, built on :focus-visible (a pseudo-class that matches a focused element only when the browser decides focus should be shown, which in practice means keyboard focus, not a mouse click on a button). Make it a thick outline in a colour that contrasts with the page, taken from a custom property so it changes with the light and dark theme. Treat hover as an enhancement: apply it only inside @media (hover: hover) and (pointer: fine) (a media query that matches when the main input can hover and is precise, such as a mouse), and never put anything a user needs behind :hover alone. Give every control the same five states: default, hover, focus-visible, active (being pressed) and disabled. Two rules carry the behaviour: the single :focus-visible rule and the hover styles placed inside the (hover: hover) query. The sections after the listing check that those two rules still hold in a dark theme, in forced-colors mode and on a touch screen.
The CSS and markup
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Focus and hover states</title>
<style>
:root {
color-scheme: light dark;
--page: #ffffff; --ink: #1f2328; --surface: #f6f8fa; --hover: #e1e6eb;
--edge: #8c959f; --focus: #0b57d0; --muted: #6e7781;
}
@media (prefers-color-scheme: dark) {
:root {
--page: #0d1117; --ink: #e6edf3; --surface: #21262d; --hover: #30363d;
--edge: #8b949e; --focus: #79b8ff; --muted: #8b949e;
}
}
body { margin: 16px; background: var(--page); color: var(--ink); font: 16px/1.5 system-ui, sans-serif; }
.btn {
min-height: 44px; padding: 0 16px; font: inherit;
color: var(--ink); background: var(--surface);
border: 1px solid var(--edge); border-radius: 8px;
}
.btn:active { background: var(--hover); }
.btn:disabled { color: var(--muted); cursor: not-allowed; }
/* Hover only where a pointer can really hover. */
@media (hover: hover) and (pointer: fine) {
.btn:hover:not(:disabled) { background: var(--hover); }
}
/* One focus treatment for every control. */
:focus-visible {
outline: 3px solid var(--focus);
outline-offset: 2px;
box-shadow: 0 0 0 2px var(--page); /* fills the gap, so the ring reads on any background */
}
/* Secondary actions: always visible unless the device can hover, and shown on keyboard focus. */
.card .actions { opacity: 1; }
@media (hover: hover) and (pointer: fine) {
.card .actions { opacity: 0; }
.card:hover .actions, .card:focus-within .actions { opacity: 1; }
}
</style>
</head>
<body>
<button class="btn" id="save" type="button">Save</button>
<button class="btn" id="off" type="button" disabled>Disabled</button>
<label>Name <input id="name" type="text"></label>
<article class="card">
<h2>Card</h2>
<div class="actions"><button class="btn" id="delete" type="button">Delete</button></div>
</article>
</body>
</html>
- Theme tokens.
--focus,--page,--surface,--hover,--edgeand--mutedare CSS custom properties: variables you define with a--name and read withvar().color-scheme: light darktells the browser the page supports both themes, so built-in parts such as form controls and scrollbars follow the theme.@media (prefers-color-scheme: dark)matches when the user's operating system is set to dark, and redefining the tokens inside it means every state works on both themes from one set of rules. A theme needs its own tokens because a colour that contrasts with white (#0b57d0) can disappear on a near-black page. The ring is#0b57d0on white and#79b8ffon#0d1117. - Focus.
outline: 3px solid var(--focus)withoutline-offset: 2px. An outline does not take up layout space, so the ring never shifts neighbours.box-shadow: 0 0 0 2px var(--page)has no offset and no blur, so it paints a solid 2px band just outside the border in the page colour. That band sits in the 2px gap thatoutline-offsetleaves, so the inner edge of the ring always borders the page colour. The same rule covers buttons, links, inputs and anything with atabindex, so the treatment is consistent. - Hover. The
.btn:hoverrule lives inside the pointer media query and excludes:disabled. Elsewhere the control keeps its resting colour. - Active.
.btn:activedarkens while pressed, which gives touch and mouse users immediate feedback without relying on hover. - Disabled. Muted text and a
not-allowedcursor; no hover change. WCAG 1.4.11 Non-text Contrast applies to "visual information required to identify user interface components and states, except for inactive components" (https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html), so a disabled control may be low-contrast, but a normal one must not be. - Secondary actions. The card's Delete button is always visible by default. Only on hover-capable devices is it faded out until the card is hovered or
:focus-within(any descendant has focus) matches, so a keyboard user who tabs to it sees it.
Why :focus-visible and not :focus
MDN: :focus-visible "applies while an element matches the :focus pseudo-class and the UA (User Agent) determines via heuristics that the focus should be made evident on the element", and "when a button is clicked using a pointing device, the focus is generally not visually indicated, but when a text box needing user input has focus, focus is indicated" (https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-visible). The test shows exactly that in all three engines: after a mouse click the button's outline is none, while a click into the text input shows the solid 3px ring, and Tab to the button shows the ring. So you keep the ring for keyboard users without the "flash" mouse users complain about, which is the usual reason developers delete outlines.
Light and dark themes
The ring has to be recomputed for each theme, not assumed. The test emulates each colour scheme, tabs to the button and reads the computed outline (rgb(11, 87, 208) in light, rgb(121, 184, 255) in dark). It also computes the contrast ratio with the WCAG relative-luminance formula: 6.39:1 for the light ring on white and 9.11:1 for the dark ring on #0d1117, both above the 3:1 that WCAG 1.4.11 asks of user-interface indicators. The button edge is 3.04:1 on white and 6.15:1 on the dark page.
Forced-colors mode (a high-contrast mode where the browser overrides author colours) is a third case. In Chromium's emulation the outline stays solid 3px, but its colour is no longer our --focus value: the browser substitutes a colour from the user's forced palette (the test prints rgba(5, 0, 73, 0.8), not rgb(11, 87, 208)), while the box-shadow computes to none. That is why the ring is an outline and the shadow is only a bonus: an indicator drawn with box-shadow alone would disappear.
Hover on touch devices
The test uses Chromium's touch emulation (a mobile profile with touch), where (hover: hover) reports false, taps Save and reads its background. A touch screen has no pointer to hover, but browsers still match :hover after a tap. MDN: "Depending on the browser, the :hover pseudo-class might never match, match only for a moment after touching an element, or continue to match even after the user has stopped touching and until the user touches another element" (https://developer.mozilla.org/en-US/docs/Web/CSS/:hover). In Chromium's emulation it is the last case: the test prints :hover matches: true after the tap, so an ungated hover colour sticks. Without the media query (the "ungated :hover" line), the button stays in its hover colour rgb(225, 230, 235) after the tap; with the shipped gated rule it returns to rgb(246, 248, 250). (The :active rule is removed in these runs so only the hover rule can change the colour.) The headless Firefox in the test image reports false for the hover query even without touch emulation, so the pointer-dependent lines are measured in Chromium and WebKit, and the focus lines in all three. In the output, read the three touch device lines by comparing Save bg at rest with after tap. In the shipped version both are rgb(246, 248, 250): :hover matches, but the colour rule sits behind the media query, so nothing changes. In the ungated version the background becomes rgb(225, 230, 235), the hover colour, and stays there. In the hover-only-reveal version Save is unchanged but the Delete action has opacity 0.
The same rule decides whether content is reachable. A version that hides actions with opacity: 0 and reveals them on .card:hover leaves the Delete button at opacity 0 on the touch profile, and also at opacity 0 when a keyboard user focuses it, in all three engines: an invisible control with focus. The shipped version has opacity 1 on the touch profile, and 1 when the button has focus on a hover-capable pointer, because :focus-within reveals it.
What to look for when critiquing existing CSS
outline: noneor*:focus { outline: 0 }with no replacement: the test replaces the focus rule withoutline: noneand the ring is gone in all three engines.:hoverdoing the only visible work: a menu, tooltip or action that appears only on hover cannot be reached by touch or keyboard.- Hover rules outside the pointer query: the colour sticks after a tap.
- A focus ring with the same colour as the control or page background in one theme (check each theme's contrast).
- Different treatments per component: one global
:focus-visiblerule is easier to keep consistent than per-component rules.
Proof in three engines
The script reads controls.html (the listing above) and builds three broken copies by text replacement: noRing swaps the :focus-visible rule for :focus { outline: none; }, ungated moves the hover rule out of the media query, and hoverOnlyReveal reveals the card actions on :hover alone. The helper ring returns an element's computed outline style, width and colour, bg its background and opacity its opacity. open creates a fresh browser context for each scenario, which is how colour scheme and touch emulation are set. Per engine it checks the ring in the light and dark schemes, then a mouse click on the button and on the text input, then Tab to the Delete button, then the noRing copy. For Chromium only it adds the desktop hover check, the three touch-device runs (with the :active rule deleted, so only the hover rule can change the colour) and forced colors. For all three engines it focuses Delete with the keyboard and reads the actions' opacity in the shipped and hover-only versions. The last lines compute the contrast ratios.
import { chromium, firefox, webkit } from 'playwright';
import { readFileSync } from 'node:fs';
const shipped = readFileSync('controls.html', 'utf8');
const noRing = shipped.replace(/:focus-visible \{[^}]*\}/, ':focus { outline: none; }');
const ungated = shipped.replace(/@media \(hover: hover\) and \(pointer: fine\) \{\s*\.btn:hover:not\(:disabled\) \{ background: var\(--hover\); \}\s*\}/, '.btn:hover { background: var(--hover); }');
const hoverOnlyReveal = shipped.replace(/\.card \.actions \{ opacity: 1; \}\s*@media \(hover: hover\) and \(pointer: fine\) \{[\s\S]*?\n \}\n/, '.card .actions { opacity: 0; }\n .card:hover .actions { opacity: 1; }\n');
const lum = (hex) => {
const c = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
.map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));
return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
};
const ratio = (a, b) => { const [x, y] = [lum(a), lum(b)].sort((p, q) => q - p); return ((x + 0.05) / (y + 0.05)).toFixed(2); };
const ring = (id) => (document.getElementById(id) && ((s) => `${s.outlineStyle} ${s.outlineWidth} ${s.outlineColor}`)(getComputedStyle(document.getElementById(id))));
const bg = (id) => getComputedStyle(document.getElementById(id)).backgroundColor;
const opacity = (sel) => getComputedStyle(document.querySelector(sel)).opacity;
for (const type of [chromium, firefox, webkit]) {
const browser = await type.launch();
const log = (...a) => console.log(type.name().padEnd(8), ...a);
const open = async (html, opts = {}) => {
const ctx = await browser.newContext(opts);
const page = await ctx.newPage();
await page.setContent(html);
return page;
};
for (const scheme of ['light', 'dark']) {
const page = await open(shipped, { colorScheme: scheme });
await page.keyboard.press('Tab');
log(`${scheme.padEnd(5)} Tab to Save ->`, await page.evaluate(ring, 'save'));
await page.close();
}
let page = await open(shipped);
await page.click('#save');
const afterClick = await page.evaluate(ring, 'save');
await page.click('#name');
log('mouse click: button ->', afterClick.split(' ').slice(0, 2).join(' '), '| text input ->', (await page.evaluate(ring, 'name')).split(' ').slice(0, 2).join(' '));
await page.keyboard.press('Tab'); // from the input to the card's Delete button
const tabbed = await page.evaluate(() => [...document.querySelectorAll('button')].map((b) => b.id + (b.disabled ? '(disabled)' : '')).join(','));
log('Tab from the input lands on:', await page.evaluate(() => document.activeElement.id), '| buttons present:', tabbed);
await page.close();
page = await open(noRing);
await page.keyboard.press('Tab');
log('focus rule replaced by outline:none ->', (await page.evaluate(ring, 'save')).split(' ').slice(0, 2).join(' '));
await page.close();
if (type === chromium) {
// Desktop pointer vs touch device
page = await open(shipped);
const before = await page.evaluate(bg, 'save');
await page.hover('#save');
log('desktop: hover changes Save background:', before, '->', await page.evaluate(bg, 'save'), '| actions opacity at rest:', await page.evaluate(opacity, '.actions'));
await page.close();
for (const [name, html] of [['gated hover (shipped)', shipped], ['ungated :hover', ungated], ['hover-only reveal', hoverOnlyReveal]]) {
// The :active rule is removed here so that only the hover rule can change the background after a tap.
page = await open(html.replace('.btn:active { background: var(--hover); }', ''), { hasTouch: true, isMobile: true, viewport: { width: 390, height: 700 } });
const rest = await page.evaluate(bg, 'save');
const actions = await page.evaluate(opacity, '.actions');
await page.tap('#save');
log(`touch device, ${name}: (hover: hover) =`, await page.evaluate(() => matchMedia('(hover: hover)').matches), '| Save bg at rest', rest, '-> after tap', await page.evaluate(bg, 'save'), '(:hover matches:', await page.evaluate(() => document.getElementById('save').matches(':hover')) + ')', '| actions opacity', actions);
await page.close();
}
}
// Keyboard reveal of the hover-only action (desktop pointer needed for the media query: Chromium and WebKit)
page = await open(shipped);
const hoverMatches = await page.evaluate(() => matchMedia('(hover: hover) and (pointer: fine)').matches);
await page.focus('#delete');
log('keyboard focus on Delete: (hover: hover) and (pointer: fine) =', hoverMatches, '| actions opacity when focused:', await page.evaluate(opacity, '.actions'));
await page.close();
page = await open(hoverOnlyReveal);
await page.focus('#delete');
log('hover-only reveal, keyboard focus on Delete: actions opacity', await page.evaluate(opacity, '.actions'));
await page.close();
if (type === chromium) {
page = await open(shipped);
await page.emulateMedia({ forcedColors: 'active' });
await page.keyboard.press('Tab');
log('forced-colors: active, Tab to Save ->', await page.evaluate(ring, 'save'), '| box-shadow:', await page.evaluate(() => getComputedStyle(document.getElementById('save')).boxShadow));
await page.close();
}
await browser.close();
}
const pairs = [['light', '#0b57d0', '#ffffff'], ['dark', '#79b8ff', '#0d1117']];
for (const [n, ringC, pageC] of pairs) console.log(`${n}: focus ring ${ringC} on page ${pageC} = ${ratio(ringC, pageC)}:1`);
console.log('light: button edge #8c959f on page #ffffff =', ratio('#8c959f', '#ffffff') + ':1', '| dark: edge #8b949e on #0d1117 =', ratio('#8b949e', '#0d1117') + ':1');
Output (one sample run):
chromium light Tab to Save -> solid 3px rgb(11, 87, 208)
chromium dark Tab to Save -> solid 3px rgb(121, 184, 255)
chromium mouse click: button -> none 0px | text input -> solid 3px
chromium Tab from the input lands on: delete | buttons present: save,off(disabled),delete
chromium focus rule replaced by outline:none -> none 0px
chromium desktop: hover changes Save background: rgb(246, 248, 250) -> rgb(225, 230, 235) | actions opacity at rest: 0
chromium touch device, gated hover (shipped): (hover: hover) = false | Save bg at rest rgb(246, 248, 250) -> after tap rgb(246, 248, 250) (:hover matches: true) | actions opacity 1
chromium touch device, ungated :hover: (hover: hover) = false | Save bg at rest rgb(246, 248, 250) -> after tap rgb(225, 230, 235) (:hover matches: true) | actions opacity 1
chromium touch device, hover-only reveal: (hover: hover) = false | Save bg at rest rgb(246, 248, 250) -> after tap rgb(246, 248, 250) (:hover matches: true) | actions opacity 0
chromium keyboard focus on Delete: (hover: hover) and (pointer: fine) = true | actions opacity when focused: 1
chromium hover-only reveal, keyboard focus on Delete: actions opacity 0
chromium forced-colors: active, Tab to Save -> solid 3px rgba(5, 0, 73, 0.8) | box-shadow: none
firefox light Tab to Save -> solid 3px rgb(11, 87, 208)
firefox dark Tab to Save -> solid 3px rgb(121, 184, 255)
firefox mouse click: button -> none 0px | text input -> solid 3px
firefox Tab from the input lands on: delete | buttons present: save,off(disabled),delete
firefox focus rule replaced by outline:none -> none 0px
firefox keyboard focus on Delete: (hover: hover) and (pointer: fine) = false | actions opacity when focused: 1
firefox hover-only reveal, keyboard focus on Delete: actions opacity 0
webkit light Tab to Save -> solid 3px rgb(11, 87, 208)
webkit dark Tab to Save -> solid 3px rgb(121, 184, 255)
webkit mouse click: button -> none 0px | text input -> solid 3px
webkit Tab from the input lands on: delete | buttons present: save,off(disabled),delete
webkit focus rule replaced by outline:none -> none 0px
webkit keyboard focus on Delete: (hover: hover) and (pointer: fine) = true | actions opacity when focused: 1
webkit hover-only reveal, keyboard focus on Delete: actions opacity 0
light: focus ring #0b57d0 on page #ffffff = 6.39:1
dark: focus ring #79b8ff on page #0d1117 = 9.11:1
light: button edge #8c959f on page #ffffff = 3.04:1 | dark: edge #8b949e on #0d1117 = 6.15:1
WebKit in Playwright is not Safari on iOS, and touch emulation in Chromium is not a real phone.
Running the code
npm init -y && npm pkg set type=module
npm i playwright@1.48.2
npx playwright install chromium firefox webkit
# save the HTML listing as controls.html next to focus_hover.mjs
node focus_hover.mjs
Run in the mcr.microsoft.com/playwright:v1.48.2-jammy image (browsers preinstalled; skip the install line there).
You work on a CMS-driven site where editors upload images with arbitrary aspect ratios. Propose a scalable solution for delivering responsive images and correct art direction: include how you would store focal points or crop variants, generate responsive sizes/formats, expose options in the CMS UI for editors, and how the front-end should select and render these resources. Discuss CDN integration and performance trade-offs.
Sample Answer
Direct answer
In plain terms: the editor uploads one photo, the site never alters it, and every smaller or re-cropped copy the page shows is produced from it by a URL.
In a content management system (CMS, the tool editors use to publish pages), store one immutable original per upload (it is never overwritten) in object storage (file storage addressed by a key, such as a cloud bucket), plus small metadata (pixel size, a focal point, optional hand-made crops, alt text). Generate every other size, crop and format on demand through an image-transform URL (a URL such as /img/42/v7/wide?w=960&fmt=avif that a transform service, a small server that resizes, crops and re-encodes images when asked, answers) with an allowlisted set of widths (a fixed list of permitted values; anything else is rejected), and let a content delivery network (CDN, a cache network close to users) hold the results. The front end renders a <picture> per slot: art-directed <source media> entries only where the CMS has an explicit crop, format <source type> entries, and an <img> with srcset in width descriptors, a hand-written sizes, and width/height (on the <img>, and on every <source> whose crop has a different aspect ratio) so the layout is stable before any file arrives. Focal point covers the "arbitrary aspect ratio" problem in general; explicit crops are reserved for the few places where the designer needs a different picture.
Data model: what the CMS stores
| Field | Purpose |
|---|---|
original_key, width, height, mime | The untouched upload in object storage; never overwritten |
focal_x, focal_y (0 to 1) | The point that must stay visible under any crop |
crops[] (name, x, y, w, h in original pixels) | Optional editor-drawn crops for named slots (wide, square, portrait) |
alt, decorative | Alt text is required unless the editor marks the image decorative; some usages may override it |
version | Bumped on any focal/crop edit; goes into every derived URL |
A focal point is cheap to author (one click) and works for every ratio, including ratios nobody planned for. Explicit crops are for art direction: a wide banner and a phone layout that show different parts of the scene.
Turning a focal point into a crop
For a target ratio, take the largest box of that ratio that fits the original, centre it on the focal point, then clamp it inside the image. Worked on a 4000x3000 original with focal point (0.7, 0.4):
- Square 1:1: box is 3000x3000. Centred x would be 0.7x4000 - 1500 = 1300, but the box may start at most at 4000 - 3000 = 1000, so x = 1000. y = 0.
- Wide 16:9: width 4000, height 4000/(16/9) = 2250. y = 0.4x3000 - 1125 = 75 (inside 0 to 750), x = 0.
- Portrait 4:5: height 3000, width 2400. x = 0.7x4000 - 1200 = 1600 (the limit is 4000 - 2400 = 1600).
export function cropFor({ width, height }, focal, ratio) {
let w = width, h = Math.round(width / ratio);
if (h > height) { h = height; w = Math.round(height * ratio); }
const x = Math.min(Math.max(Math.round(focal.x * width - w / 2), 0), width - w);
const y = Math.min(Math.max(Math.round(focal.y * height - h / 2), 0), height - h);
return { x, y, w, h };
}
In the browser, the same focal point also drives object-fit: cover; object-position: 70% 40% when a fixed-size box has to crop a file whose ratio differs (a card grid), so no server crop is needed there.
Generating sizes and formats
- Width ladder: a short fixed list, for example 320, 640, 960, 1280, 1920, 2560. Reject any other
wvalue at the transform service. Unbounded widths let anyone mint unlimited cache entries and CPU work by editing a URL. - Formats: AVIF and WebP (newer image file formats)
<source type>entries ahead of a JPEG<img>. MDN: "If the user agent does not support the given type, the<source>element is skipped." Putting the format in the URL (fmt=avif) is simpler than choosing by theAcceptrequest header (the header in which the browser lists the image types it can decode), because every file then has its own URL and the markup says exactly which file each<source>points to. - Variant count: 6 widths x 3 formats x 3 crops (wide, square, portrait) is 54 possible derivatives per image, 10,800 across 200 images. On-demand generation means only the combinations actually requested ever exist. Pre-generate (warm) only the hero set when an editor publishes, so the first visitor does not pay the cold transform (the first request for a URL that nothing has generated or cached yet, which has to wait for the resize).
- Encoding cost differs by format and settings, so measure encode time and file size on your own images before choosing quality settings.
CMS editing UI
- After upload, show the image with a draggable focal marker and live previews of each named ratio (the computed crops above).
- For named slots, a "custom crop" button opens a crop tool locked to that slot's ratio; leaving it off falls back to the focal-point crop.
- Warn when the original is smaller than the largest slot (a 1000px upload in a hero that needs 1920 will be upscaled).
- Require alt text or an explicit "decorative" toggle; allow a per-placement alt override because the same photo means different things in different articles.
Front end: select and render
<picture>
<!-- explicit crop exists for small screens; width/height give the browser this crop's ratio (1:1) before any file loads -->
<source media="(max-width: 600px)" type="image/avif" width="1000" height="1000"
srcset="/img/42/v7/square?w=320&fmt=avif 320w, /img/42/v7/square?w=640&fmt=avif 640w"
sizes="100vw">
<source media="(max-width: 600px)" type="image/webp" width="1000" height="1000"
srcset="/img/42/v7/square?w=320&fmt=webp 320w, /img/42/v7/square?w=640&fmt=webp 640w"
sizes="100vw">
<source type="image/avif"
srcset="/img/42/v7/wide?w=960&fmt=avif 960w, /img/42/v7/wide?w=1920&fmt=avif 1920w"
sizes="(min-width: 1200px) 1200px, 100vw">
<img alt="Chef plating a dish" width="1920" height="1080"
src="/img/42/v7/wide?w=1920&fmt=jpeg"
srcset="/img/42/v7/wide?w=960&fmt=jpeg 960w, /img/42/v7/wide?w=1920&fmt=jpeg 1920w"
sizes="(min-width: 1200px) 1200px, 100vw">
</picture>
A small component generates this from the asset record, so editors never touch markup. The caller supplies sizes for its layout slot, because only the page knows how wide the slot is. The width/height on the <img> carry the ratio of the default crop (16:9), and each <source> with a different crop carries its own, because the <img> attributes alone would reserve a 16:9 box and the square file would then push the content below it down when it arrives (the test below measures this: 225px reserved, 400px after load, in all three engines). Above the fold, the hero image gets fetchpriority="high" (MDN: "Fetch the image at a high priority relative to other images") and everything else gets loading="lazy" ("Defers loading the image until it reaches a calculated distance from the viewport").
How the CDN fits the markup
- The CDN stores each derived file under its URL. The URL shape
/img/<id>/v<version>/<crop>?w=&fmt=therefore gives every version of every crop its own address: editing a crop bumpsversion, the component writes the new URL into thesrcset, and pages show the new file without anyone clearing a cache. - The width ladder and the crop names are what bound the number of distinct URLs the CDN and the transform service ever see, which is why the
wallowlist and the named crops belong in the markup generator and not in free-form editor input. - The cost to watch is the cold transform on first request: it is paid once per distinct URL, so a short ladder and a warmed hero set keep it off the pages that matter most.
Stable layout for a 200-thumbnail gallery
A gallery of 200 thumbnails shows why the stored dimensions belong in the markup: the browser can reserve each image's space before any file arrives only if it knows the ratio. Give each thumbnail width/height (or CSS aspect-ratio) from the stored crop ratio and height: auto in CSS. MDN: including them "enables the aspect ratio of the image to be calculated by the browser prior to the image being loaded". web.dev advises: "Always include width and height size attributes on your images" and treats a Cumulative Layout Shift (CLS, a score for unexpected movement of visible content) of 0.1 or less as the target. The test below holds all 200 images back, measures the page height, releases them, and measures again in three engines; a second check does the same for one art-directed image.
import { chromium, firefox, webkit } from 'playwright';
import assert from 'node:assert/strict';
// Crop box for a target ratio: centre the box on the focal point, then clamp it inside the original.
export function cropFor({ width, height }, focal, ratio) {
let w = width, h = Math.round(width / ratio);
if (h > height) { h = height; w = Math.round(height * ratio); }
const x = Math.min(Math.max(Math.round(focal.x * width - w / 2), 0), width - w);
const y = Math.min(Math.max(Math.round(focal.y * height - h / 2), 0), height - h);
return { x, y, w, h };
}
const original = { width: 4000, height: 3000 };
const focal = { x: 0.7, y: 0.4 };
for (const [name, ratio] of [['square 1:1', 1], ['wide 16:9', 16 / 9], ['portrait 4:5', 4 / 5]]) {
console.log(name.padEnd(11), JSON.stringify(cropFor(original, focal, ratio)));
}
assert.deepEqual(cropFor(original, focal, 1), { x: 1000, y: 0, w: 3000, h: 3000 });
assert.deepEqual(cropFor(original, focal, 16 / 9), { x: 0, y: 75, w: 4000, h: 2250 });
const thumbs = (withSize) => Array.from({ length: 200 }, (_, i) =>
`<img src="/t${i}.svg" alt="Photo ${i}" ${withSize ? 'width="800" height="600"' : ''}>`).join('');
const page = (withSize) => `<!doctype html><meta charset="utf-8">
<style>
body { margin: 0 }
.grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px }
.grid img { display: block; width: 100%; height: auto }
.focal { width: 300px; height: 300px; object-fit: cover; object-position: 70% 40% }
</style>
<div class="grid">${thumbs(withSize)}</div>
<img class="focal" id="f" src="/t0.svg" alt="Cover crop" width="800" height="600">`;
// Art direction at a 400px viewport: the square file is chosen. Does the box reserved before load match it?
const artPage = (sourceSize) => `<!doctype html><style>body { margin: 0 } img { display: block; width: 100%; height: auto }</style>
<picture><source media="(max-width: 600px)" srcset="/square.svg"${sourceSize ? ' width="1000" height="1000"' : ''}>
<img id="art" alt="" src="/wide.svg" width="1920" height="1080"></picture>`;
const svg = (w, h) => `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><rect width="${w}" height="${h}" fill="#789"/></svg>`;
for (const [bname, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const result = {};
for (const withSize of [true, false]) {
const ctx = await browser.newContext({ viewport: { width: 808, height: 600 } });
const p = await ctx.newPage();
let release; const gate = new Promise(r => (release = r));
await p.route('http://cms.test/**', async r => {
const u = new URL(r.request().url());
if (u.pathname === '/') return r.fulfill({ contentType: 'text/html', body: page(withSize) });
await gate; // hold every image back so the "before load" layout can be measured
return r.fulfill({ contentType: 'image/svg+xml',
body: '<svg xmlns="http://www.w3.org/2000/svg" width="800" height="600"><rect width="800" height="600" fill="#789"/></svg>' });
});
await p.goto('http://cms.test/', { waitUntil: 'domcontentloaded' });
const before = await p.evaluate(() => document.documentElement.scrollHeight);
release();
await p.waitForFunction(() => [...document.images].every(i => i.complete && i.naturalWidth > 0));
const after = await p.evaluate(() => document.documentElement.scrollHeight);
const f = await p.evaluate(() => {
const el = document.getElementById('f'), r = el.getBoundingClientRect(), cs = getComputedStyle(el);
return { w: r.width, h: r.height, pos: cs.objectPosition, fit: cs.objectFit, grid: document.querySelector('.grid').getBoundingClientRect().height };
});
result[withSize] = { before, after, f };
await ctx.close();
}
const a = result[true], b = result[false];
console.log(bname.padEnd(8), `with width/height: ${a.before} -> ${a.after}`, `| without: ${b.before} -> ${b.after}`,
`| cover box ${a.f.w}x${a.f.h} ${a.f.fit} ${a.f.pos} | grid ${a.f.grid}`);
assert.equal(a.before, a.after); // reserved space: nothing moves when files arrive
assert.notEqual(b.before, b.after); // no reserved space: the page grows after load
assert.equal(a.f.grid, 7742); // 50 rows x 147px + 49 gaps x 8px
assert.equal(a.f.pos, '70% 40%');
assert.equal(a.f.fit, 'cover');
const art = {};
for (const sourceSize of [true, false]) {
const ctx = await browser.newContext({ viewport: { width: 400, height: 800 } });
const p = await ctx.newPage();
let release; const gate = new Promise(r => (release = r));
await p.route('http://cms.test/**', async r => {
const u = new URL(r.request().url());
if (u.pathname === '/') return r.fulfill({ contentType: 'text/html', body: artPage(sourceSize) });
await gate;
return r.fulfill({ contentType: 'image/svg+xml', body: u.pathname === '/square.svg' ? svg(1000, 1000) : svg(1920, 1080) });
});
await p.goto('http://cms.test/', { waitUntil: 'domcontentloaded' });
const box = () => p.evaluate(() => document.getElementById('art').getBoundingClientRect().height);
const before = await box();
release();
await p.waitForFunction(() => document.getElementById('art').naturalWidth > 0);
art[sourceSize] = { before, after: await box() };
await ctx.close();
}
console.log(bname.padEnd(8), `art-directed square crop, 400px viewport, image box height: with <source> width/height ${art[true].before} -> ${art[true].after}`,
`| <img> attributes only ${art[false].before} -> ${art[false].after}`);
assert.equal(art[true].before, art[true].after);
assert.notEqual(art[false].before, art[false].after);
await browser.close();
}
console.log('all assertions passed');
Run in the Playwright 1.48.2 image (WebKit here is Playwright's build, not iOS Safari); the page heights differ by a pixel or two between engines:
square 1:1 {"x":1000,"y":0,"w":3000,"h":3000}
wide 16:9 {"x":0,"y":75,"w":4000,"h":2250}
portrait 4:5 {"x":1600,"y":0,"w":2400,"h":3000}
chromium with width/height: 8046 -> 8046 | without: 696 -> 8046 | cover box 300x300 cover 70% 40% | grid 7742
chromium art-directed square crop, 400px viewport, image box height: with <source> width/height 400 -> 400 | <img> attributes only 225 -> 400
firefox with width/height: 8047 -> 8047 | without: 697 -> 8047 | cover box 300x300 cover 70% 40% | grid 7742
firefox art-directed square crop, 400px viewport, image box height: with <source> width/height 400 -> 400 | <img> attributes only 225 -> 400
webkit with width/height: 8048 -> 8048 | without: 698 -> 8048 | cover box 300x300 cover 70% 40% | grid 7742
webkit art-directed square crop, 400px viewport, image box height: with <source> width/height 400 -> 400 | <img> attributes only 225 -> 400
all assertions passed
With the attributes the page height is identical before and after the images arrive; without them it grows from under 700px to over 8,000px. For the art-directed image, the <source> attributes keep the box at 400px before and after; with only the 16:9 <img> attributes it is 225px until the square file arrives.
The heights can be reproduced by hand. The viewport is 808px wide with a 4-column grid and 8px gaps, so each column is (808 - 3 x 8) / 4 = 196px, and a 4:3 thumbnail at that width is 196 x 600 / 800 = 147px tall. 200 thumbnails in 4 columns make 50 rows: 50 x 147 + 49 x 8 = 7,350 + 392 = 7,742px. The cover-fit image below the grid adds 300px, giving 8,042px; the engines report 8,046, 8,047 and 8,048 because that last image is an inline element, so its line box leaves a few pixels of space below it that differs slightly with each engine's font metrics (the grid itself measures exactly 7,742px in all three, the grid figure at the end of each first printed line, and asserted). Without the attributes every thumbnail is 0px tall until its file arrives, so the grid holds only its 49 x 8 = 392px of gaps: 392 + 300 plus the same few pixels is the 696 to 698 printed.
Trade-offs and pitfalls
- Pre-generate vs on-demand: pre-generating everything is predictable but multiplies storage and slows publishing; on-demand with a CDN is cheaper but has cold-miss latency and needs the width allowlist. For a media-heavy CMS, on-demand plus a warmed hero set is the better default; flip to full pre-generation if the transform service cannot meet latency on cold misses.
- A wrong
sizessilently over-downloads, and a focal point on a poor crop looks like a bug to editors, so the preview step matters. - Never bake text or UI into the cropped image; it will be cut on some ratios.
Running the code
npm init -y && npm i playwright@1.48.2 # inside mcr.microsoft.com/playwright:v1.48.2-jammy
# add "type": "module" to package.json, save the test as cms-image.mjs
node cms-image.mjs
In plain HTML, CSS, and vanilla JavaScript implement an accessible 'Skip to main content' link that appears as the first focusable element, becomes visible when focused, and moves keyboard focus to the main content container. Also describe how this pattern should adapt for a single-page application where the main content id may change on navigation.
Sample Answer
Direct answer
A skip link is the first link in the page, parked above the viewport with CSS (not display: none, which would remove it from the tab order), moved into view by :focus, and pointed at the main container. The container needs tabindex="-1", which makes an element focusable by script or by a link but keeps it out of the Tab sequence, so activating the link puts keyboard focus on <main> and the next Tab lands on the first control inside it. In a single-page application (SPA, a site that swaps content without reloading), the link must look up the current <main> when it is activated rather than trust an id written into the HTML, because the id can change on every navigation.
The code
index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Home | Acme</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<a class="skip-link" href="#main-home">Skip to main content</a>
<header>
<nav aria-label="Main">
<a href="/" data-route="home">Home</a>
<a href="/settings" data-route="settings">Settings</a>
<a href="/billing" data-route="billing">Billing</a>
</nav>
</header>
<main id="main-home" tabindex="-1">
<h1 tabindex="-1">Home</h1>
<p>Welcome back. <a href="/settings" data-route="settings">Review your settings</a>.</p>
</main>
<script src="app.js"></script>
</body>
</html>
styles.css:
.skip-link {
position: absolute;
top: 0; left: 8px;
padding: 8px 12px;
background: #fff; color: #000; border: 2px solid #000;
transform: translateY(-150%); /* parked above the viewport, still focusable */
}
.skip-link:focus { transform: translateY(0); } /* visible while it has keyboard focus */
app.js:
const skipLink = document.querySelector('.skip-link');
// 1. The skip link looks up the current <main> when it is activated, so a changed id does not matter.
skipLink.addEventListener('click', (event) => {
event.preventDefault(); // no hash change (hash routers would misread it)
const main = document.querySelector('main');
main.focus(); // main has tabindex="-1": focusable by script, not by Tab
main.scrollIntoView();
});
// 2. A minimal client-side router that replaces <main> and gives it a new id each time.
const pages = {
home: '<p>Welcome back. <a href="/settings" data-route="settings">Review your settings</a>.</p>',
settings: '<p>Change your <a href="#email">email</a> or <a href="#password">password</a>.</p>',
billing: '<p>Your plan renews monthly. <a href="#invoices">Invoices</a></p>',
};
const titles = { home: 'Home', settings: 'Settings', billing: 'Billing' };
function render(route) {
const main = document.createElement('main');
main.id = `main-${route}`; // different id on every route
main.tabIndex = -1;
main.innerHTML = `<h1 tabindex="-1">${titles[route]}</h1>${pages[route]}`;
document.querySelector('main').replaceWith(main);
skipLink.href = `#${main.id}`; // keep the fallback href truthful
document.title = `${titles[route]} | Acme`; // the new page gets its own title
main.querySelector('h1').focus(); // focus starts at the new page's heading
}
document.addEventListener('click', (event) => {
const link = event.target.closest('a[data-route]');
if (!link) return;
event.preventDefault();
history.pushState({}, '', link.getAttribute('href'));
render(link.dataset.route);
});
Why each part is there
- First in the DOM. The skip link comes before the header and navigation, so it is the first stop for a keyboard user. WCAG success criterion 2.4.1 (Bypass Blocks) says: "A mechanism is available to bypass blocks of content that are repeated on multiple web pages." A skip link is the usual such mechanism: it lets a keyboard user jump past the navigation that every page repeats, instead of pressing Tab through it each time.
- Parked, not hidden.
transform: translateY(-150%)moves the link above the top edge of the page. It still takes part in focus order..skip-link:focusresets the transform, so the link appears the moment a keyboard user lands on it, with a solid background and border so it is readable over whatever is behind. tabindex="-1"on<main>. Without it a non-interactive element cannot take focus, somain.focus()does nothing and focus stays on the skip link (theDROP=tabindexrun below shows exactly that).-1is right,0is wrong:0would add<main>to the Tab sequence for everyone.preventDefault()and a script focus. The link'shref="#main-home"already works as a fallback without JavaScript: with the click handler removed (DROP=nojs), focus still moved to<main>in all three engines. The handler adds one thing: the URL does not gain a#main-homefragment. That matters in an SPA, where a hash router (one that keeps the current page in the URL fragment, the part after#, and reacts to the browser'shashchangeevent) could treat the new fragment as a navigation, and for anyone who copies the address bar.- Scrolling.
main.scrollIntoView()brings the container to the top so sighted keyboard users see where focus went.
Adapting it for a single-page application
- Look the target up at activation time.
document.querySelector('main')is evaluated on click, so it finds whichever<main>exists now, whatever its id. The router inapp.jsreplaces<main>with a new element and a new id (main-home,main-settings), so a handler holding the old element or a fixedgetElementById('main-home')would fail after the first navigation (theDROP=dynamicrun does exactly that). - Keep the fallback
hreftruthful.render()rewrites the skip link'shrefto the new id, so middle-click, copy-link and the no-script path stay correct. - Decide where focus goes after a route change. A normal page load resets focus to the top; an SPA swap does not, so focus can be left on a link that was activated or on something that no longer exists. This code focuses the new page's
<h1>(which carriestabindex="-1") and updatesdocument.title. The consequence, shown in the run: the skip link is then behind the user. Four Shift+Tab presses get from the new heading back to it (Billing, Settings, Home, then the skip link). Moving focus to the top of the document instead would put the skip link one Tab away but loses the "you are here" cue. Focusing the heading is the choice here because the user has just chosen to go somewhere, and the next Tab continues through the new content. - Persistent layout stays outside the swapped region. The skip link and navigation are not re-rendered, so their focus state and listeners survive; only
<main>changes.
How the router code reads, line by line: the delegated click listener on document catches every click, and event.target.closest('a[data-route]') walks up from the clicked element to the nearest link carrying a data-route attribute (or returns null, in which case the handler stops). event.preventDefault() cancels the browser's normal page load for that link. history.pushState({}, '', href) changes the address bar to the new path without loading a page. link.dataset.route reads the data-route attribute (settings). In render(), document.createElement('main') builds the replacement element, replaceWith(main) swaps it into the old one's place in the DOM, and main.querySelector('h1').focus() moves keyboard focus to the new heading (which has tabindex="-1" so a script may focus it).
Checking it in real browsers
The harness serves the three files from a local HTTP server and drives the page with real keyboard presses in Chromium, Firefox and WebKit (Playwright's WebKit build, which is not Safari on iOS). It asserts: the link is parked above the viewport (bottom <= 0); the first Tab focuses it and it is inside the 600px-high viewport; Enter moves focus to <main> without adding a URL fragment; the next Tab lands inside the content, not the navigation; activating the Settings link with the keyboard swaps <main>, changes its id, the title and the focus target; and after that the skip link, reached with Shift+Tab, focuses the new <main>. It also asserts that the skip link's href is rewritten to the new id. A failing run exits with status 1. DROP=visible, dynamic, tabindex, nojs or href removes one piece.
skip-check.mjs:
import fs from 'node:fs';
import http from 'node:http';
import { chromium, firefox, webkit } from 'playwright';
const read = (f) => fs.readFileSync('skip/' + f, 'utf8');
let css = read('styles.css'), js = read('app.js'), html = read('index.html');
const drop = process.env.DROP;
if (drop === 'visible') css = css.replace('.skip-link:focus { transform: translateY(0); }', '');
if (drop === 'dynamic') js = js.replace("document.querySelector('main')", "document.getElementById('main-home')");
if (drop === 'tabindex') html = html.replace('<main id="main-home" tabindex="-1">', '<main id="main-home">');
if (drop === 'href') js = js.replace(/ skipLink\.href = .*\n/, '');
if (drop === 'nojs') js = js.replace(/skipLink\.addEventListener\('click'[\s\S]*?\n\}\);\n/, '');
const server = http.createServer((req, res) => {
const route = ['/settings', '/billing', '/'].includes(req.url);
const file = route ? 'index.html' : req.url.slice(1);
const body = file === 'index.html' ? html : file === 'styles.css' ? css : file === 'app.js' ? js : null;
if (body === null) { res.statusCode = 404; return res.end(); }
res.setHeader('content-type', file.endsWith('.css') ? 'text/css' : file.endsWith('.js') ? 'text/javascript' : 'text/html');
res.end(body);
}).listen(0);
const base = `http://localhost:${server.address().port}`;
let bad = 0;
const check = (name, label, pass, detail = '') => {
if (!pass) bad++;
if (name === 'chromium' || !pass) console.log(name.padEnd(8), label.padEnd(36), detail, pass ? 'ok' : 'FAIL');
};
const where = (p) => p.evaluate(() => { const a = document.activeElement; return a === document.body ? 'body' : (a.id || a.className || a.tagName.toLowerCase() + ':' + a.textContent.trim().slice(0, 12)); });
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const p = await browser.newPage({ viewport: { width: 800, height: 600 } });
const skipTop = () => p.evaluate(() => { const r = document.querySelector('.skip-link').getBoundingClientRect(); return { top: r.top, bottom: r.bottom }; });
await p.goto(base + '/');
const parked = await skipTop();
check(name, 'parked above the viewport', parked.bottom <= 0, `bottom=${parked.bottom}`);
await p.keyboard.press('Tab');
const shown = await skipTop();
check(name, 'first Tab: skip link, visible', (await where(p)) === 'skip-link' && shown.top >= 0 && shown.bottom <= 600, `top=${shown.top} bottom=${shown.bottom}`);
await p.keyboard.press('Enter');
check(name, 'Enter: focus moves to <main>', (await where(p)) === 'main-home', await where(p));
check(name, 'Enter: URL hash untouched', (await p.evaluate(() => location.hash)) === '', `hash='${await p.evaluate(() => location.hash)}'`);
await p.keyboard.press('Tab');
check(name, 'next Tab: inside content, not nav', (await where(p)).startsWith('a:Review'), await where(p));
// Single-page app: navigate with the keyboard, then use the skip link on the new page
await p.goto(base + '/');
await p.keyboard.press('Tab'); await p.keyboard.press('Tab'); await p.keyboard.press('Tab'); // skip link, Home, Settings
await p.keyboard.press('Enter');
const after = await p.evaluate(() => ({ id: document.querySelector('main').id, title: document.title, focus: document.activeElement.tagName + ':' + document.activeElement.textContent, path: location.pathname, skipHref: document.querySelector('.skip-link').getAttribute('href') }));
check(name, 'route change: id, title, focus', after.id === 'main-settings' && after.title === 'Settings | Acme' && after.focus === 'H1:Settings' && after.path === '/settings' && after.skipHref === '#main-settings', JSON.stringify(after));
await p.keyboard.press('Shift+Tab'); // focus is on the h1 in <main>; go back to the nav
let steps = 1;
while ((await where(p)) !== 'skip-link' && steps < 10) { await p.keyboard.press('Shift+Tab'); steps++; }
check(name, 'Shift+Tab reaches skip link', (await where(p)) === 'skip-link', `${steps} presses`);
await p.keyboard.press('Enter');
check(name, 'skip link finds the NEW main', (await where(p)) === 'main-settings', await where(p));
await browser.close();
}
server.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
Run in the Playwright 1.48.2 container, it prints (Chromium rows; the other engines print only failures):
chromium parked above the viewport bottom=-19 ok
chromium first Tab: skip link, visible top=0 bottom=38 ok
chromium Enter: focus moves to <main> main-home ok
chromium Enter: URL hash untouched hash='' ok
chromium next Tab: inside content, not nav a:Review your ok
chromium route change: id, title, focus {"id":"main-settings","title":"Settings | Acme","focus":"H1:Settings","path":"/settings","skipHref":"#main-settings"} ok
chromium Shift+Tab reaches skip link 4 presses ok
chromium skip link finds the NEW main main-settings ok
all checks pass in chromium, firefox and webkit
Each removal fails. The failing Chromium rows from each DROP value (Firefox and WebKit fail the same checks, with slightly different pixel values):
DROP=visible chromium first Tab: skip link, visible top=-57 bottom=-19 FAIL
DROP=dynamic chromium skip link finds the NEW main skip-link FAIL
DROP=tabindex chromium Enter: focus moves to <main> skip-link FAIL
DROP=tabindex chromium next Tab: inside content, not nav a:Home FAIL
DROP=nojs chromium Enter: URL hash untouched hash='#main-home' FAIL
DROP=href chromium route change: id, title, focus {... "skipHref":"#main-home"} FAIL
In words: without the :focus rule the link is still above the viewport (bottom=-19) while it has focus, so it is invisible; with a fixed id in the handler, focus stays on the skip link after the route change; without tabindex="-1", Enter leaves focus on the skip link and the next Tab goes to the Home link; without the click handler the URL gains #main-home; without the line that rewrites the skip link's href, the route-change row fails because the link still points at #main-home. Repeated runs of the unmodified harness printed the success line every time.
Pitfalls
- Hiding the link with
display: none,visibility: hiddenor a zero-size clip that is never undone makes it unreachable, which defeats the purpose. - Putting the link after the header means keyboard users tab through the navigation first.
- A target that is not focusable: the link appears to work and focus does not move.
- Two
<main>elements, or a<main>re-created on route change withouttabindex="-1", break the pattern silently. - Moving focus on every route change without a reason for the user to expect it can be disorienting; pair it with a visible change (heading, title).
Running the code
mkdir skip-demo && cd skip-demo && mkdir skip
# save index.html, styles.css and app.js into skip/, and skip-check.mjs here
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 skip-check.mjs # DROP=visible | dynamic | tabindex | nojs | href removes one piece
You have the following images on a product page: a company logo in the header, a decorative SVG divider, a product photo showing multiple items, an infographic chart, and an icon-only button. For each image describe the appropriate alt text (or why it should be empty) and where a long description belongs for complex images like charts. Explain trade-offs between concise and verbose alt text.
Sample Answer
Direct answer
Alt text (the alt attribute on an img, which becomes the image's accessible name, the text a screen reader or other assistive technology announces in its place) answers one question: what does this image do on this page? That gives a different answer for each of the five images.
| Image | Treatment | Text |
|---|---|---|
| Company logo in the header, linking to the home page | alt names the link's destination | alt="Trailhead Outfitters home" |
| Decorative SVG divider | Hidden from assistive technology | inline svg with aria-hidden="true" (or <img alt="">, or a CSS background) |
| Product photo showing several items | alt says what the photo adds that the page text does not | alt="The set packed together: a 1.5 litre pot, a folding stove, two mugs and a spork" |
| Infographic chart | Short alt that identifies it, plus a long description in visible page content that the image points to | alt of 15 words, a 22-word summary and a data table |
| Icon-only button (the cart) | The button gets the name, the icon is hidden | aria-label="Cart, 3 items" on the button |
Each case in detail
Four attributes in the page do the work. aria-hidden="true" removes an element from the accessibility tree (the browser's version of the page that assistive technology reads), so nothing is announced for it. aria-label gives an element a name directly, as a string. aria-describedby points at another element's id and uses that element's text as a longer description, announced after the name. focusable="false" on an svg stops older Internet Explorer and Edge from making the drawing a Tab stop; it is harmless in current browsers.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Basecamp Cooking Set</title>
</head>
<body>
<header>
<!-- The logo is the only content of the link, so the alt text names the destination. -->
<a href="/"><img src="logo.svg" width="120" height="32" alt="Trailhead Outfitters home"></a>
<!-- Icon-only button: the name comes from aria-label; the drawing is hidden from assistive technology. -->
<button type="button" aria-label="Cart, 3 items">
<svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M3 4h3l3 11h9l2-8H7" fill="none" stroke="currentColor" stroke-width="2"/></svg>
</button>
</header>
<main>
<h1>Basecamp Cooking Set</h1>
<!-- Decorative divider: nothing to say, so it is hidden from assistive technology. -->
<svg width="300" height="8" viewBox="0 0 300 8" aria-hidden="true" focusable="false"><path d="M0 4h300" stroke="#bbb" stroke-width="2"/></svg>
<!-- Informative photo: say what is shown that the page text does not already say. -->
<img src="set.svg" width="320" height="200"
alt="The set packed together: a 1.5 litre pot, a folding stove, two mugs and a spork">
<ul>
<li>1.5 litre aluminium pot</li>
<li>Folding stove</li>
</ul>
<!-- Complex image: short alt, a visible summary it points to, and the full data as a table. -->
<figure>
<img src="chart.svg" width="320" height="160"
alt="Bar chart of pack weight for five cooking sets, from 410 g to 980 g"
aria-describedby="chart-summary">
<figcaption>
<span id="chart-summary">Weight rises from the Solo set (410 g) to the Family set (980 g); the Basecamp set is third at 640 g.</span>
<a href="#chart-data">Full data table</a>
</figcaption>
</figure>
<table id="chart-data">
<caption>Pack weight by cooking set</caption>
<thead><tr><th scope="col">Set</th><th scope="col">Weight (g)</th></tr></thead>
<tbody>
<tr><td>Solo</td><td>410</td></tr>
<tr><td>Duo</td><td>520</td></tr>
<tr><td>Basecamp</td><td>640</td></tr>
<tr><td>Group</td><td>810</td></tr>
<tr><td>Family</td><td>980</td></tr>
</tbody>
</table>
</main>
</body>
</html>
Logo. When an image is the only content of a link, its text alternative is the link's name, so it should say where the link goes. The W3C Web Accessibility Initiative (WAI) functional-images tutorial gives the example of the W3C logo alone in a link to the W3C home page, which gets the alt text "W3C home", and says the text alternative "should convey the action that will be initiated" (https://www.w3.org/WAI/tutorials/images/functional/). If the page also has visible link text beside the logo that says the same thing, the logo becomes decorative and gets an empty alt, so the same words are not read twice. If the logo is not a link, the alt is the company name.
Decorative divider. The WAI decorative-images tutorial says "a null (empty) alt text should be provided" for a decorative img and "Where possible, decorative images should be provided using CSS background images instead" (https://www.w3.org/WAI/tutorials/images/decorative/). For an inline SVG, which has no alt attribute, aria-hidden="true" removes it from the accessibility tree. The script checks this with Playwright's role query (which computes roles and names from the DOM): as shipped the page exposes 3 images (logo, photo, chart); deleting aria-hidden from the divider raises that to 4; replacing the divider with <img alt=""> leaves it at 3. Omitting the alt attribute altogether is not the same as writing alt="": the empty value is the explicit statement "nothing to announce".
Product photo with several items. The alt describes what a sighted shopper learns from the photo, not the file ("photo of..." adds nothing, since the role already announces an image). WAI's informative-images tutorial says the text alternative "should convey the meaning or content that is displayed visually" and "typically isn't a literal description of the image" (https://www.w3.org/WAI/tutorials/images/informative/). The page text above lists only the pot and stove, so the alt names the other items (mugs, spork) and the fact that they pack together: 16 words. If the visible text already listed every item, the alt could shrink to "The set packed together", because the same facts would otherwise be read twice.
Infographic chart. The data cannot fit in an alt attribute usefully, because alt is one plain string with no structure: no rows, no headings, no way to jump to a value. The pattern is a two-part alternative, which WAI's complex-images tutorial states as "a two-part text alternative is required", the first part "the short description to identify the image" and the second "the long description" (https://www.w3.org/WAI/tutorials/images/complex/). The page does it in three layers:
alt(15 words) identifies the image and its headline range: "Bar chart of pack weight for five cooking sets, from 410 g to 980 g".- A visible summary of 22 words in the
figcaptionstates the trend, andaria-describedby="chart-summary"ties the image to it. In Chromium's accessibility snapshot the image has that summary as its description; with the attribute removed the description is empty (nullin the output). - The full data is a real
tablewith acaptionandth scope="col"headers, linked from the figure ("Full data table").
The long description is visible, adjacent text rather than a hidden attribute, so people who cannot see the chart well, people who prefer numbers, and search engines all get it, and it is easy to keep up to date. WAI lists the same placements for a long description: a text link next to the image, a figure with figcaption, or describing its location in the alt. The script also checks that the numbers agree: the alt's "410 g to 980 g" is the minimum and maximum of the table, the summary names the lightest (Solo, 410 g) and the heaviest (Family, 980 g) and gives Basecamp's rank (third of five) correctly.
Icon-only button. An svg inside a button is decoration; the button needs the name. aria-label="Cart, 3 items" gives the action or object plus the current state; name what it does or opens, not what it looks like ("Cart", not "Shopping cart icon"). The test finds one button with that name and one link named by the logo alt in all three engines.
Concise versus verbose alt text
| Concise (logo: 3 words) | Verbose (photo: 16 words, chart: 15 words plus a 22-word summary) | |
|---|---|---|
| Strength | Cheap to hear on every visit, no repetition | Carries information the page does not state elsewhere |
| Cost | Can drop the detail the image exists to deliver | Re-announced each time the image is met, can duplicate adjacent text |
| Right for | Functional images, repeated images, images whose point is already in the text | Informative images that carry unique content |
The rule of thumb is to put in alt exactly what the image contributes and nothing the nearby text already says, and to move anything with structure (data, steps, multi-part descriptions) into real markup. Counts in the output (3, 16, 15, 22 words and 10 table cells) come from the script, so they match the page exactly.
Proof
The script loads the page above in Chromium, Firefox and WebKit and computes the facts quoted: the exposed images, the link and button names, the agreement between alt, summary and table, the word counts and the effect of removing each decision. It prints these values and compares them in code; it does not stop on a mismatch, so read the printed true values. The page refers to logo.svg, set.svg and chart.svg, which do not exist on disk, so page.route('**/*.svg', ...) intercepts those requests and answers each with a small generated placeholder SVG; this keeps the images loading, so they appear in the tree as real images without needing image files. evaluateAll runs a function in the page over every element a locator matches and returns the results, here a text label per image; page.$$eval and page.$eval do the same for a CSS selector. The last section deletes one decision at a time (the divider's aria-hidden, the divider as an empty-alt img, the aria-describedby) and recounts. The output below is identical on repeated runs. Playwright is a library that drives real browsers from a script; its role query (getByRole) asks the browser's accessibility tree for elements of a given role, which is not a screen reader, and these checks do not show how any particular screen reader speaks the page.
import { chromium, firefox, webkit } from 'playwright';
import { readFileSync } from 'node:fs';
const html = readFileSync('product_page.html', 'utf8');
const svg = (label) => `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="200"><rect width="320" height="200" fill="#cde"/><text x="10" y="20">${label}</text></svg>`;
const words = (s) => s.trim().split(/\s+/).length;
for (const type of [chromium, firefox, webkit]) {
const browser = await type.launch();
const page = await browser.newPage();
const log = (...a) => console.log(type.name().padEnd(8), ...a);
await page.route('**/*.svg', (r) => r.fulfill({ contentType: 'image/svg+xml', body: svg(new URL(r.request().url()).pathname) }));
await page.goto('about:blank');
await page.setContent(html, { waitUntil: 'load' });
// What the accessibility tree exposes: every image, link and button with its computed name.
const images = await page.getByRole('img').evaluateAll((els) => els.map((e) => `${e.tagName.toLowerCase()}[${e.getAttribute('alt') ?? e.getAttribute('aria-label') ?? ''}]`));
const link = await page.getByRole('link', { name: 'Trailhead Outfitters home' }).count();
const button = await page.getByRole('button', { name: 'Cart, 3 items' }).count();
const hiddenSvgs = await page.locator('svg[aria-hidden="true"]').count();
const svgAsImg = await page.locator('svg').and(page.getByRole('img')).count();
log('images in the accessibility tree:', images.length, '| link named by its logo alt:', link, '| icon button named by aria-label:', button, '| aria-hidden svgs:', hiddenSvgs, 'of which exposed as images:', svgAsImg);
// The numbers in the short alt text must agree with the table.
const data = await page.$$eval('#chart-data tbody tr', (rows) => rows.map((r) => [r.cells[0].textContent, Number(r.cells[1].textContent)]));
const weights = data.map((d) => d[1]);
const alt = await page.$eval('img[aria-describedby]', (e) => e.alt);
const summary = await page.$eval('#chart-summary', (e) => e.textContent);
const ok = alt.includes(`${Math.min(...weights)} g to ${Math.max(...weights)} g`) && alt.includes(`${data.length === 5 ? 'five' : '?'} cooking sets`);
const lightest = data.reduce((a, b) => (b[1] < a[1] ? b : a)), heaviest = data.reduce((a, b) => (b[1] > a[1] ? b : a));
const rank = [...weights].sort((a, b) => a - b).indexOf(640) + 1;
log(`chart alt agrees with the table: ${ok} | summary names lightest ${lightest[0]} ${lightest[1]} g, heaviest ${heaviest[0]} ${heaviest[1]} g, Basecamp rank ${rank} of ${data.length} | summary matches: ${summary.includes('Solo set (410 g)') && summary.includes('Family set (980 g)') && summary.includes('third at 640 g')}`);
log(`lengths in words: logo alt ${words(await page.$eval('header img', (e) => e.alt))}, photo alt ${words(await page.$eval('main > img', (e) => e.alt))}, chart alt ${words(alt)}, chart summary ${words(summary)}, table cells ${data.length * 2}`);
// Delete one decision at a time to show the page changes.
const treeImages = async (h) => { await page.setContent(h, { waitUntil: 'load' }); return page.getByRole('img').count(); };
const noHide = html.replace('<svg width="300" height="8" viewBox="0 0 300 8" aria-hidden="true"', '<svg width="300" height="8" viewBox="0 0 300 8"');
const imgDivider = html.replace(/<svg width="300"[^>]*>.*?<\/svg>/, '<img src="divider.svg" alt="">');
const noDescribed = html.replace(' aria-describedby="chart-summary"', '');
log(`images exposed: as shipped ${await treeImages(html)} | divider without aria-hidden ${await treeImages(noHide)} | divider as <img alt=""> ${await treeImages(imgDivider)}`);
await page.setContent(noDescribed, { waitUntil: 'load' });
const plain = type === chromium ? JSON.stringify((await page.accessibility.snapshot({ interestingOnly: false })).children.flatMap(function w(n) { return [n, ...(n.children || []).flatMap(w)]; }).filter((n) => n.name && n.name.startsWith('Bar chart')).map((n) => n.description ?? null)) : 'n/a';
if (type === chromium) log('chart description without aria-describedby:', plain);
await page.setContent(html, { waitUntil: 'load' });
if (type === chromium) {
const snap = await page.accessibility.snapshot({ interestingOnly: false });
const found = [];
(function walk(n) { if (n.role === 'img' || n.role === 'image') found.push(`${n.role}: name="${n.name}"${n.description ? ` description="${n.description.slice(0, 30)}..."` : ''}`); (n.children || []).forEach(walk); })(snap);
log('accessibility snapshot images:', found.length);
for (const f of found) log(' ', f);
}
await browser.close();
}
chromium images in the accessibility tree: 3 | link named by its logo alt: 1 | icon button named by aria-label: 1 | aria-hidden svgs: 2 of which exposed as images: 0
chromium chart alt agrees with the table: true | summary names lightest Solo 410 g, heaviest Family 980 g, Basecamp rank 3 of 5 | summary matches: true
chromium lengths in words: logo alt 3, photo alt 16, chart alt 15, chart summary 22, table cells 10
chromium images exposed: as shipped 3 | divider without aria-hidden 4 | divider as <img alt=""> 3
chromium chart description without aria-describedby: [null]
chromium accessibility snapshot images: 3
chromium image: name="Trailhead Outfitters home"
chromium image: name="The set packed together: a 1.5 litre pot, a folding stove, two mugs and a spork"
chromium image: name="Bar chart of pack weight for five cooking sets, from 410 g to 980 g" description="Weight rises from the Solo set..."
firefox images in the accessibility tree: 3 | link named by its logo alt: 1 | icon button named by aria-label: 1 | aria-hidden svgs: 2 of which exposed as images: 0
firefox chart alt agrees with the table: true | summary names lightest Solo 410 g, heaviest Family 980 g, Basecamp rank 3 of 5 | summary matches: true
firefox lengths in words: logo alt 3, photo alt 16, chart alt 15, chart summary 22, table cells 10
firefox images exposed: as shipped 3 | divider without aria-hidden 4 | divider as <img alt=""> 3
webkit images in the accessibility tree: 3 | link named by its logo alt: 1 | icon button named by aria-label: 1 | aria-hidden svgs: 2 of which exposed as images: 0
webkit chart alt agrees with the table: true | summary names lightest Solo 410 g, heaviest Family 980 g, Basecamp rank 3 of 5 | summary matches: true
webkit lengths in words: logo alt 3, photo alt 16, chart alt 15, chart summary 22, table cells 10
webkit images exposed: as shipped 3 | divider without aria-hidden 4 | divider as <img alt=""> 3
Running the code
npm init -y && npm pkg set type=module
npm i playwright@1.48.2
npx playwright install chromium firefox webkit
# save the HTML listing as product_page.html next to alt_text.mjs
node alt_text.mjs
Run in the mcr.microsoft.com/playwright:v1.48.2-jammy image (browsers preinstalled; skip the install line there).
Compare and contrast the CSS sizing units: px, %, em, rem, vw, and vh. For each unit describe how it is calculated, typical use cases in responsive layouts (e.g., layout sizing, typography, spacing), and one common pitfall. Provide a concise example where combining units (for example rem + vw) achieves a fluid, responsive result.
Sample Answer
Direct answer
px is a fixed CSS pixel. % is a share of a parent value. em is a multiple of the current element's font size. rem is a multiple of the root element's font size. vw and vh are 1% of the viewport (the visible area of the browser window) width and height. Use rem for type and global spacing so everything follows the user's font setting, em for spacing that should scale with a component's own text, % for widths inside a flexible parent, vw and vh for sizes tied to the window, and px for things that must not scale, such as 1px borders. A fluid result comes from mixing a stable unit with a viewport unit: font-size: calc(1rem + 0.5vw).
The six units
| Unit | Calculated from | Typical use | Common pitfall |
|---|---|---|---|
px | A fixed length (one CSS pixel) | Hairline borders, shadows, small fixed details | A font-size in px on html overrides the user's chosen text size, and px text does not respond to the browser's default font size setting |
% | A share of the containing block, which is usually the parent's box (width: 50% is half the parent's width) | Column widths, fluid images (max-width: 100%) | Percent height needs a parent with a definite height (one the browser can compute without looking at the content, such as a px height or a percentage of a parent that has one); on an auto-height parent it is ignored, so height: 50% gives a box as tall as its content |
em | MDN: "the calculated font-size of the element. If used on the font-size property itself, it represents the inherited font-size of the element." | Padding, margins and icon sizes that should scale with their own text | Compounds through nesting: a nested element's em is relative to its parent's already-multiplied size (worked below) |
rem | MDN: "the font-size of the root element (typically <html>)... A common browser default is 16px, but user-defined preferences may modify this." | Font sizes and a global spacing scale | Setting html { font-size: 62.5% } or px on the root changes what 1rem means everywhere |
vw | 1% of the viewport width: 50vw on an 800px viewport is 400px | Full-bleed sections, the fluid term in clamp() | Alone, it does not follow the user's font settings; combine it with a rem term (see the pitfalls) |
vh | 1% of the viewport height | Hero sections, full-height panels | On phones the visible height changes as the browser's address bar shows and hides; MDN says vh is equivalent to lvh (the large viewport, with browser interface retracted), so content can be hidden while the interface is shown, and dvh (dynamic) follows the interface but "can cause the content to resize while a user is scrolling"; svh is the small viewport, measured with the browser interface fully shown |
Worked example: compounding and the fluid mix
The rem + vw combination in its shortest form is one declaration, font-size: calc(1rem + 0.5vw);, which the arithmetic below evaluates to 18px at a 400px window and 22px at 1200px. The listing also checks how em compounds and how the root size flows through.
html { font-size: 100%; } /* 16px unless the user changed the browser default */
body { margin: 0; }
.parent { width: 400px; }
.half { width: 50%; }
.em-a { font-size: 1.5em; padding: 1em; }
.em-b { font-size: 1.5em; padding: 1em; } /* compounds: 1.5 x 1.5 x 16 */
.rem-a, .rem-b { font-size: 1.5rem; padding: 1rem; } /* does not compound */
.vw { width: 50vw; height: 50vh; }
.fluid { font-size: calc(1rem + 0.5vw); }
.tall { height: 50%; } /* parent has auto height */
emnesting:.em-bis inside.em-a, and both sayfont-size: 1.5em. The outer box is 16 x 1.5 = 24px, so the inner one is 24 x 1.5 = 36px. Thepadding: 1emon the inner box is 36px as well, becauseemon a non-font property uses the element's own font size.remdoes not compound: both.rem-aand.rem-bare 1.5 x 16 = 24px however deeply they sit.%:.halfis 50% of a 400px parent, so 200px.- Viewport units: on an 800 x 600 window, 50vw is 400px and 50vh is 300px.
- Fluid type:
calc(1rem + 0.5vw)is 16 + 0.005 x 400 = 18px at a 400px-wide window and 16 + 0.005 x 1200 = 22px at 1200px. The1rempart keeps responding to the user's setting and thevwpart adds the fluid growth. - Respecting preferences: changing the root size to 20px (what a larger browser default text size does when the page does not set its own root size) turns the nested rem box into 30px and the nested em box into 45px (20 x 1.5 x 1.5).
import { chromium, firefox, webkit } from 'playwright';
import assert from 'node:assert/strict';
const css = `
html { font-size: 100%; } /* 16px unless the user changed the browser default */
body { margin: 0; }
.parent { width: 400px; }
.half { width: 50%; }
.em-a { font-size: 1.5em; padding: 1em; }
.em-b { font-size: 1.5em; padding: 1em; } /* compounds: 1.5 x 1.5 x 16 */
.rem-a, .rem-b { font-size: 1.5rem; padding: 1rem; } /* does not compound */
.vw { width: 50vw; height: 50vh; }
.fluid { font-size: calc(1rem + 0.5vw); }
.tall { height: 50%; } /* parent has auto height */
`;
const html = `<!doctype html><style>${css}</style>
<div class="parent"><div class="half" id="half">x</div><div class="tall" id="tall">text</div></div>
<div class="em-a"><div class="em-b" id="em">em</div></div>
<div class="rem-a"><div class="rem-b" id="rem">rem</div></div>
<div class="vw" id="vw"></div><p class="fluid" id="fluid">fluid</p>`;
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const page = await browser.newPage({ viewport: { width: 800, height: 600 } });
await page.setContent(html);
const px = (sel, prop) => page.evaluate(([s, p]) => parseFloat(getComputedStyle(document.querySelector(s))[p]), [sel, prop]);
assert.equal(await px('#half', 'width'), 200); // 50% of the 400px parent
assert.equal(await px('#em', 'fontSize'), 36); // 16 * 1.5 * 1.5
assert.equal(await px('#em', 'paddingLeft'), 36); // 1em = the element's own 36px
assert.equal(await px('#rem', 'fontSize'), 24); // 1.5 * 16, whatever the nesting
assert.equal(await px('#vw', 'width'), 400); // 50 * 8px
assert.equal(await px('#vw', 'height'), 300); // 50 * 6px
assert.ok(await px('#tall', 'height') < 40); // % height of an auto-height parent is ignored: the box is as tall as its text
await page.setViewportSize({ width: 400, height: 600 });
const small = await px('#fluid', 'fontSize');
await page.setViewportSize({ width: 1200, height: 600 });
const large = await px('#fluid', 'fontSize');
assert.deepEqual([small, large], [18, 22]); // 16 + 2, 16 + 6
// The user's default font size lives on the root element: rem and em follow it, px does not.
await page.evaluate(() => { document.documentElement.style.fontSize = '20px'; });
assert.equal(await px('#rem', 'fontSize'), 30);
assert.equal(await px('#em', 'fontSize'), 45);
console.log(name, '| em nested:36px rem nested:24px | fluid 400px->' + small + 'px, 1200px->' + large + 'px | root 20px: rem 30px, em 45px');
// Change the inner em box to rem: its font size no longer compounds with the outer box.
await page.setViewportSize({ width: 800, height: 600 });
await page.setContent(html.replace(".em-b { font-size: 1.5em;", ".em-b { font-size: 1.5rem;"));
console.log(name, '| .em-b changed to rem: nested box is', await px('#em', 'fontSize') + 'px, so the 36px assertion would fail');
await browser.close();
}
Printed output:
chromium | em nested:36px rem nested:24px | fluid 400px->18px, 1200px->22px | root 20px: rem 30px, em 45px
chromium | .em-b changed to rem: nested box is 24px, so the 36px assertion would fail
firefox | em nested:36px rem nested:24px | fluid 400px->18px, 1200px->22px | root 20px: rem 30px, em 45px
firefox | .em-b changed to rem: nested box is 24px, so the 36px assertion would fail
webkit | em nested:36px rem nested:24px | fluid 400px->18px, 1200px->22px | root 20px: rem 30px, em 45px
webkit | .em-b changed to rem: nested box is 24px, so the 36px assertion would fail
The second line per engine changes the inner box .em-b from em to rem: its font size drops from 36px to 24px, because it no longer multiplies the outer box's 24px, so the 36px assertion would fail. That is the compounding the em row refers to.
Choosing relative or absolute units
- Typography:
rem(orclamp()built onrem). It follows the user's preference. - Spacing: a
remscale for page-level rhythm;eminside a component whose padding should grow with its text (buttons, badges). - Icons:
em, so an icon beside text keeps its proportion when the text size changes. - Borders, outlines, shadows:
px. - Layout widths:
%,fr, ormin()/max(), not fixed px, so content can flex.fris a grid-only unit meaning one share of the free space in a grid container;min(a, b)andmax(a, b)take the smaller or larger of two lengths;clamp(low, preferred, high)is a value that followspreferredbut never goes belowlowor abovehigh. The six units above cover most work; these are the tools for the cases they do not.
Pitfalls summary
- Nested
emcompounds; useremfor font sizes and keepemfor lengths on the same element. - Never size text in
vwalone; always include aremterm so zoom and user settings still work. Forclamp(), MDN advises that "the maximum allowed value is a relative length unit that is no less than twice the minimum allowed value" so text can scale to 200% when zoomed. - Prefer
dvhorsvh(or a flex layout withmin-height) overvhfor full-height mobile sections. - Percent heights need a definite parent height.
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 units.mjs
node units.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.
Unlock Full Question Bank
Get access to all Frontend Fundamentals: HTML, CSS, and Responsive Styling interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.