← Interview prep

HTML & CSS interview questions

Semantic HTML, CSS layout, and CSS interview depth.

193 questions · Page 7 of 10

Want the full pack? Interview packs · Mock interview · Mentora

Page 7 of 10

Questions 121–140 of 193 · 0 of 20 on this page marked learned

121.html-css-0121Mediummid

How do you serve different background images by screen size and density, and when is a background image the wrong choice?

Change background-image inside min-width and min-resolution media queries, or use image-set(), and always set a background colour. Backgrounds have no alt text and no loading attribute, so use img or picture for content and backgrounds for decoration.

Full answer

A CSS background image is chosen by CSS rules, so you can change it with media queries.

  • By width: set a small image first, and replace it inside @media (min-width: 700px) with a larger one. Only the image of the matching rule is downloaded in the usual case.
  • By density: @media (min-resolution: 2dppx) selects a high-density image for sharp screens. image-set() does the same inside one declaration: background-image: image-set(url(a.jpg) 1x, url(b.jpg) 2x). Check the support table for the unprefixed form, and put a plain url() declaration before it as a fallback.
  • Always set a background-color close to the image average, so text stays readable before the image loads or if it fails.

Limits of background images, which matter in an interview:

  • They are not part of the content. Screen readers ignore them, there is no alt, and they do not show in print by default.
  • They cannot be lazy loaded with an attribute, and the browser finds them late, after it has parsed the CSS. For the main picture on a page, this delays the largest paint. A real img with srcset is found early and works with loading and fetchpriority.
  • Use img or picture for content such as a photo of a product or a person. Use a background for decoration, such as a pattern or a header texture.

At a width of 800px the large image is used, and at 400px the small one. The hero has a role and a label here because it carries meaning, which is a sign that an img element would be better.

If an image is the main content, use img with alt.

html
<style>
  .hero { height: 80px; background-color: #678; background-size: cover; background-image: url(/img/hero-small.jpg); }
  @media (min-width: 700px) { .hero { background-image: url(/img/hero-large.jpg); } }
  .dense { height: 40px; background-image: url(/img/pattern-1x.png); }
  @media (min-resolution: 2dppx) { .dense { background-image: url(/img/pattern-2x.png); } }
</style>
<div class="hero" id="hero" role="img" aria-label="Students in a classroom"></div>
<div class="dense" id="dense"></div>

The image files are placeholders. The check read the computed background image at 400px and 800px wide, and at a pixel ratio of 2. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Switch background-image in media queries.
  • min-resolution and image-set serve sharper images.
  • Set a background colour as a fallback.
  • Backgrounds have no alt text and are found late.
  • Content belongs in img; decoration in CSS.

Common mistakes

  • Using a background image for important content, which gives it no alt text.
  • Forgetting a background colour, so text is unreadable while the image loads.
  • Using a large background image for the first paint with no way to set its priority.

Follow-ups

  • Why is a background image found later than an img element?
  • What does image-set() do?

Tips

  • Show both ways to switch: media query width and resolution.
  • End on the rule: content is an img, decoration is a background.
122.html-css-0122Hardsenior

A script that resizes many boxes is slow. What is layout thrashing, and how do you fix it?

Layout thrashing is repeated forced layout caused by alternating style writes and layout reads such as offsetWidth in a loop. Batch all reads first and all writes after, avoid measuring by using CSS, and animate transform and opacity.

Full answer

The browser does not recalculate layout after every style change. It waits and does the work once, before the next paint. But some JavaScript reads force it to calculate the layout at once, so the answer is correct. Examples: offsetHeight, offsetWidth, getBoundingClientRect(), scrollTop and getComputedStyle(el).height.

Layout thrashing happens when a loop mixes reads and writes. A write (such as el.style.width = ...) makes the layout dirty. The next read forces a full layout. If this repeats for 100 elements, the browser does 100 layouts instead of one. On a large page, each layout is expensive.

Fixes:

  1. Batch. First read everything you need into variables, then write everything. The browser does one layout for the reads, and one for the paint.
  2. Avoid the reads. Use CSS (Flexbox, Grid, aspect-ratio) to size things, so no script needs to measure.
  3. Schedule writes with requestAnimationFrame, so they run once per frame.
  4. Animate transform and opacity, which do not need layout.
  5. Use ResizeObserver or IntersectionObserver instead of reading sizes in scroll handlers.

You can find the problem in the performance panel. Look for purple "Layout" blocks, often marked as forced reflow, with a warning and the line of code that caused them.

Both functions do the same visible work. The first reads and writes in turns, so each read forces a layout. The second reads all widths first and then writes them. In Chrome, thrash() caused about as many layouts as there are boxes, and batched() caused only a few.

Measure on a real page, because the cost depends on how big and complex the layout is.

html
<div id="host"></div>
<script>
  for (let i = 0; i < 40; i++) { const d = document.createElement("div"); d.className = "box"; d.textContent = "x"; host.append(d); }
  const boxes = [...document.querySelectorAll(".box")];
  function thrash() {
    boxes.forEach(b => { b.style.width = (b.offsetWidth + 1) + "px"; });
  }
  function batched() {
    const widths = boxes.map(b => b.offsetWidth);
    boxes.forEach((b, i) => { b.style.width = (widths[i] + 1) + "px"; });
  }
</script>

The layout counts were read from the Chrome DevTools protocol while each function ran, so the numbers come from the browser and not from timing. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Reads like offsetHeight force a synchronous layout.
  • Mixing reads and writes in a loop repeats the layout.
  • Batch reads, then writes.
  • Prefer CSS sizing over measuring.
  • Use the performance panel to find forced reflows.

Common mistakes

  • Reading offsetHeight or similar properties inside a loop that also writes styles.
  • Using scroll handlers that measure many elements on every event.
  • Guessing at the cause without looking at the performance panel.

Follow-ups

  • Which properties force layout when read?
  • How does requestAnimationFrame help?

Tips

  • Define it as a loop of write, read, write, read, and say why a read forces layout.
  • Give the batching fix first, then say that CSS often removes the need to measure.
123.html-css-0123Hardsenior

What is the critical CSS strategy, and what are its costs?

Critical CSS inlines the rules needed for the first screen in the head and loads the rest without blocking, for example with a media="print" link switched to all on load, plus a noscript fallback. It speeds the first paint but must be kept in step with the pages and measured.

Full answer

A stylesheet loaded with <link rel="stylesheet"> blocks rendering. The browser will not paint the page until it has downloaded and parsed it, because it needs the styles to paint correctly. A large stylesheet on a slow network delays the first paint.

The critical CSS strategy splits the CSS in two parts.

  1. Critical CSS: the rules needed to draw what is visible without scrolling (the layout, header, fonts and hero). It is small and goes into a style element in the head, so the first paint needs no extra request.
  2. The rest of the CSS: loaded without blocking. A common pattern is <link rel="stylesheet" href="rest.css" media="print" onload="this.media='all'">. A stylesheet with a media type that does not match is downloaded at low priority and does not block. When it loads, the script switches the media to all and it applies. Add a <noscript> link as a fallback for users with scripts off. Another pattern is rel="preload" as="style" with a switch in onload.

Costs and risks:

  • The critical part must be kept in step with the pages. Tools can extract it at build time, but the result depends on the viewport sizes you choose. Missing rules cause a flash of unstyled content, and layout shifts when the rest loads.
  • The inline part is not cached by itself, and is sent again with every page. Keep it small, about the size of a few network packets.
  • The same rules are sent twice (inline and in the full file) unless the build removes them.
  • With HTTP/2 and good caching, and with small sheets, the gain can be small. Measure with real pages and a slow network before and after.

The hero is styled at once by the inline rules. The paragraph gets its colour only after the second stylesheet has loaded and its media was switched to all.

Test with network throttling, and check that the page does not jump when the rest of the styles arrive.

html
<style>
  body { margin: 0; font: 16px sans-serif; }
  .hero { height: 60px; background: #cde; }
</style>
<link rel="stylesheet" href="/css/rest.css" media="print" onload="this.media='all'" id="rest">
<noscript><link rel="stylesheet" href="/css/rest.css"></noscript>
<div class="hero">Hero</div>
<p class="late" id="p">Styled by the late stylesheet</p>

The stylesheet file is a small placeholder served by a local test server. The check read the media value and the colour after the load. Real network timing was not measured. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Normal stylesheets block rendering.
  • Inline the small critical part in the head.
  • Load the rest with media="print" and an onload switch, plus noscript.
  • Keep critical CSS in step with the pages.
  • Measure with a slow network before and after.

Common mistakes

  • Inlining the whole stylesheet, which makes every page heavy and uncached.
  • Extracting critical CSS for one viewport size and breaking others.
  • Forgetting the noscript fallback.

Follow-ups

  • Why does a stylesheet with media="print" not block rendering?
  • How do you stop a layout shift when the late CSS loads?

Tips

  • Explain why CSS blocks rendering first, then the split.
  • Say that the benefit must be measured, not assumed.
124.html-css-0124Easyfresher

How do a CSS reset, normalize.css and a small modern reset compare, and which would you start a project with?

A reset removes browser defaults, normalize keeps useful defaults and fixes differences, and a modern minimal reset is a few rules for common problems. Start small: border-box sizing, a body reset, fluid media and form font inheritance, placed first with low specificity.

Full answer

Every browser has a default stylesheet. It gives headings a size, lists a bullet and the body an 8px margin. The defaults are mostly the same across browsers, but not exactly, and some form elements differ.

  • A reset removes the defaults. The classic version sets margin, padding and font size to zero or inherit on almost everything. You then style everything from nothing. The cost is that you must restyle lists, headings and form controls, and the reset can remove useful things, such as the focus outline.
  • Normalize keeps useful defaults and fixes the differences and bugs between browsers. A heading still looks like a heading. It is a good base for content sites. It is a larger file than a small reset.
  • A modern minimal reset is a short set of rules that fix the common pain points and nothing more. Browsers are much closer today than in the past, so most projects need only a few lines.

A sensible start for a new project is a short reset:

  • *, *::before, *::after { box-sizing: border-box; } so widths include padding and borders.
  • body { margin: 0; line-height: 1.5; }.
  • img, svg, video { display: block; max-width: 100%; height: auto; } so media does not overflow and has no gap under it.
  • input, button, select, textarea { font: inherit; } so form controls use the page font.
  • @media (prefers-reduced-motion: reduce) rules to calm animations, when the project needs them.

Put these in an early layer or at the top of the file, so every other rule can override them easily. Use :where() to keep their specificity at zero.

The input is exactly 100px wide with its padding and border inside. The button uses the page font. The second image is shrunk to its 200px parent, and height: auto lets its height follow the real shape of the picture.

A heavy reset is rarely needed today. Choose the smallest base that solves the problems you have.

html
<style>
  *, *::before, *::after { box-sizing: border-box; }
  body { margin: 0; line-height: 1.5; font-family: Georgia, serif; }
  :where(img, svg, video) { display: block; max-width: 100%; height: auto; }
  :where(input, button, select, textarea) { font: inherit; }
</style>
<input id="i" style="width:100px;padding:10px;border:2px solid #000">
<button id="b" type="button">Go</button>
<img id="img" alt="" width="600" height="100" src="/a.png" style="width:600px;">
<div style="width:200px"><img id="img2" alt="" src="/a.png" width="600" height="100"></div>

Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • A reset removes defaults; normalize makes them consistent.
  • Browsers are closer today, so a small reset is often enough.
  • box-sizing: border-box and fluid media are the common rules.
  • Form controls need font: inherit.
  • Keep reset rules first and low in specificity.

Common mistakes

  • Using a heavy reset that removes the focus outline and list semantics visuals, then forgetting to restore them.
  • Putting the reset at the end of the file, where it overrides component styles.
  • Copying a large reset without knowing what it changes.

Follow-ups

  • Why set box-sizing: border-box on everything?
  • Why make the reset rules zero specificity?

Tips

  • Describe the three options in one line each.
  • Say that you would start with a few lines and add rules only for real problems.
125.html-css-0125Mediummid

How do you check colour contrast for accessibility, and what ratios are required?

WCAG AA asks for 4.5:1 for normal text, 3:1 for large text and 3:1 for meaningful UI parts such as borders and focus rings. The ratio comes from relative luminance. Check all states and themes, do not rely on colour alone, and use tools together with your own eyes.

Full answer

Contrast is the difference in brightness between text and its background. Low contrast is hard to read for people with low vision, for people in bright light and for many others. The Web Content Accessibility Guidelines (WCAG) set minimum ratios, measured from 1:1 (no contrast) to 21:1 (black on white).

Common level AA targets:

  • Normal text: at least 4.5:1.
  • Large text (about 24px, or 19px and bold): at least 3:1.
  • User interface parts and graphics that carry meaning, such as an input border, a focus ring or an icon: at least 3:1 against what is next to them.
  • Logos and purely decorative items are exempt. Disabled controls are also exempt, although a very faint look is still unkind.

The ratio uses the relative luminance of the two colours: (L1 + 0.05) / (L2 + 0.05), where L1 is the lighter. Luminance comes from the sRGB values after converting each channel to a linear value and weighting the green channel most.

Practical points:

  • Check all states: hover, focus, visited, disabled placeholder and error text.
  • Text over images and gradients needs a check at the worst spot, or a solid overlay behind the text.
  • Do not use colour alone to give meaning. Add text, an icon or a pattern as well.
  • With a dark theme, check every pair again.
  • Browser DevTools show the ratio in the colour picker, and automated tools find many problems, but they cannot judge everything, so also look at the page by eye.

Black on white gives 21.00. Grey #767676 on white gives 4.54, which passes for normal text. The slightly lighter #777777 gives 4.48, which fails by a very small amount.

Use the result as a guide, and test the real page, because anti-aliasing and font weight also affect how readable text is.

html
<p id="out"></p>
<script>
  const lin = c => { c /= 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; };
  const lum = ([r, g, b]) => 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
  function ratio(a, b) {
    const [hi, lo] = [lum(a), lum(b)].sort((x, y) => y - x);
    return (hi + 0.05) / (lo + 0.05);
  }
  window.r1 = ratio([0, 0, 0], [255, 255, 255]);
  window.r2 = ratio([0x76, 0x76, 0x76], [255, 255, 255]);
  window.r3 = ratio([0x77, 0x77, 0x77], [255, 255, 255]);
  out.textContent = [r1, r2, r3].map(x => x.toFixed(2)).join(" / ");
</script>

Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Normal text needs 4.5:1; large text needs 3:1.
  • UI parts and meaningful graphics need 3:1.
  • The ratio is (L1 + 0.05) / (L2 + 0.05).
  • Check hover, focus, error and dark theme states.
  • Do not use colour alone to show meaning.

Common mistakes

  • Using light grey text on white for hints and placeholders.
  • Checking only the default state and not hover, focus or disabled states.
  • Placing text on a photo with no overlay and checking at the easiest spot.

Follow-ups

  • How do you check text on a gradient?
  • What contrast does a focus ring need?

Tips

  • Give the three numbers: 4.5, 3 and 3.
  • Say that colour alone must not carry meaning.
126.html-css-0126Hardsenior

How do you manage keyboard focus when a custom overlay opens and closes?

Move focus into the overlay, make the rest of the page inert, allow Escape and a close button, and return focus to the control that opened it when it closes. Give the overlay a dialog role, aria-modal and a name. A native dialog with showModal does most of this for you.

Full answer

A native dialog opened with showModal() handles most of this for you (see the question on the native dialog). If you must build your own overlay, you take on four jobs.

  1. Move focus into the overlay when it opens. Focus the first useful control, or the heading if the content is long, with tabindex="-1" on it.
  2. Keep focus inside while it is open. The old way is a script that catches Tab on the last element and sends it to the first. The modern way is to make everything else inert. The inert attribute makes an element and its children not focusable, not clickable and hidden from assistive technology. Set inert on the page content behind the overlay (the overlay must not be inside that part).
  3. Let the user close it with the Escape key and with a visible close button.
  4. When it closes, remove inert and return focus to the control that opened it. Without this, focus falls back to the top of the page, and keyboard users lose their place.

Add role="dialog", aria-modal="true" and an accessible name with aria-labelledby. Mark the background as not scrollable if needed, for example with overflow: hidden on the body, and restore it on close.

Pitfalls: opening several overlays at once, removing the control that opened it from the page while the overlay is open (then there is nowhere to return to), and forgetting that a script may need to restore inert on every code path that closes the overlay.

On opening, focus moves to the Close button, and the buttons behind cannot receive focus. Pressing Escape or Close hides the overlay and puts focus back on the Open button.

Test with the keyboard alone and with a screen reader. Where possible, use the native dialog instead.

html
<main id="page"><button id="openBtn" type="button">Open</button><button id="behind" type="button">Behind</button></main>
<div id="ov" role="dialog" aria-modal="true" aria-labelledby="t" hidden>
  <h2 id="t">Settings</h2>
  <button id="closeBtn" type="button">Close</button>
</div>
<script>
  openBtn.addEventListener("click", () => { ov.hidden = false; page.inert = true; closeBtn.focus(); });
  function shut() { ov.hidden = true; page.inert = false; openBtn.focus(); }
  closeBtn.addEventListener("click", shut);
  document.addEventListener("keydown", e => { if (e.key === "Escape" && !ov.hidden) shut(); });
</script>

Checked with real key presses in Chrome. No screen reader was run. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Focus must move into the overlay on open.
  • inert makes the background unfocusable and hidden to assistive tools.
  • Escape and a close button must close it.
  • Return focus to the control that opened it.
  • Prefer native dialog where possible.

Common mistakes

  • Not returning focus to the control that opened it on close.
  • Putting the overlay inside the element that is set to inert, so it cannot be used either.
  • Closing the overlay in one code path and forgetting to remove inert.

Follow-ups

  • What does the inert attribute do?
  • Why prefer the native dialog element?

Tips

  • List the four jobs: move in, keep in, allow close, return focus.
  • Name inert as the modern replacement for focus trap scripts.
127.html-css-0127Hardsenior

Build a tab component. Which roles, attributes and keys does it need?

Use a tablist of tab buttons with aria-selected and aria-controls, tabpanels with aria-labelledby and hidden, and a roving tabindex. Arrow keys move between tabs, Home and End jump, and the selected state is styled from aria-selected.

Full answer

Tabs show one panel at a time. The ARIA tabs pattern has fixed parts.

  • A container with role="tablist" holds the tabs. Each tab is a button with role="tab".
  • Each tab has aria-controls pointing to its panel and aria-selected="true" or "false".
  • Each panel has role="tabpanel", aria-labelledby pointing to its tab, and the hidden attribute when it is not selected.
  • Roving tabindex: only the selected tab has tabindex="0". The others have tabindex="-1". Tab moves focus into the tab list once, then on to the panel. The arrow keys move between tabs.

Keyboard behaviour:

  • Right arrow moves to the next tab, and wraps from the last to the first. Left arrow does the reverse.
  • Home and End go to the first and last tab.
  • With automatic activation, focus and selection move together. This is simple and good when panels show instantly. With manual activation, the arrows only move focus, and Enter or Space selects. This is better when a panel is slow to load.

When there is only a little content, headings and sections can be better than tabs, and an accordion is easier on small screens. Tabs hide content, so do not hide anything important.

Style the selected tab by [aria-selected="true"], so that the visual and the announced state are the same. Keep a visible focus style.

After focusing the first tab and pressing Right, the Syllabus tab is selected and its panel is shown. Pressing Right on the last tab wraps to the first.

Test with a screen reader too, since support for roles varies a little between readers.

html
<div role="tablist" aria-label="Course info" id="tl">
  <button role="tab" id="t1" aria-controls="p1" aria-selected="true" tabindex="0">Overview</button>
  <button role="tab" id="t2" aria-controls="p2" aria-selected="false" tabindex="-1">Syllabus</button>
  <button role="tab" id="t3" aria-controls="p3" aria-selected="false" tabindex="-1">Reviews</button>
</div>
<div role="tabpanel" id="p1" aria-labelledby="t1">Overview text</div>
<div role="tabpanel" id="p2" aria-labelledby="t2" hidden>Syllabus text</div>
<div role="tabpanel" id="p3" aria-labelledby="t3" hidden>Reviews text</div>
<script>
  const tabs = [...tl.querySelectorAll('[role=tab]')];
  function select(t) {
    tabs.forEach(x => {
      const on = x === t;
      x.setAttribute("aria-selected", on); x.tabIndex = on ? 0 : -1;
      document.getElementById(x.getAttribute("aria-controls")).hidden = !on;
    });
    t.focus();
  }
  tl.addEventListener("click", e => { const t = e.target.closest("[role=tab]"); if (t) select(t); });
  tl.addEventListener("keydown", e => {
    const i = tabs.indexOf(document.activeElement); if (i < 0) return;
    const to = { ArrowRight: (i + 1) % tabs.length, ArrowLeft: (i + tabs.length - 1) % tabs.length, Home: 0, End: tabs.length - 1 }[e.key];
    if (to !== undefined) { e.preventDefault(); select(tabs[to]); }
  });
</script>

Checked with real key presses in Chrome. No screen reader was run. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • tablist, tab and tabpanel roles with aria-controls and aria-labelledby.
  • Only the selected tab has tabindex 0.
  • Arrow keys move between tabs; Home and End jump.
  • Automatic or manual activation.
  • Style from aria-selected.

Common mistakes

  • Making every tab focusable with Tab, so users must tab through all tabs.
  • Hiding panels with CSS only and forgetting aria-selected.
  • Using div elements for tabs with no keyboard handling.

Follow-ups

  • What is roving tabindex?
  • When would you choose manual activation?

Tips

  • Name the roles and the roving tabindex in the first sentences.
  • Mention both automatic and manual activation.
128.html-css-0128Easyfresher

Build an accordion with a button, aria-expanded and a panel. How does it differ from details?

Put a button inside a heading, set aria-expanded on the button and hide the panel with the hidden attribute, toggling both in a short script. details and summary give the same result with no script and are the first choice for simple cases.

Full answer

An accordion is a list of headings that each open and close a panel. The simple, accessible pattern uses these parts:

  • A heading element for each item, such as h3, so that screen reader users can move by heading.
  • A real button inside the heading. It is focusable and works with Enter and Space, with no extra code.
  • aria-expanded="false" or "true" on the button tells assistive technology the state.
  • aria-controls can point to the panel. Its support is uneven, so the aria-expanded state matters most.
  • The panel is hidden with the hidden attribute when closed. A hidden panel is not focusable and is not read.

A short script toggles the attribute and the hidden state. The CSS can read the attribute, for example to rotate an arrow.

How is it different from details and summary? A details element does the same job with no JavaScript and keeps its state in the browser. It is the first choice for simple cases such as a list of questions. A custom accordion gives more control, such as animating the height, letting only one panel stay open, or reading the state in a framework. If you only need "one open at a time", note that the name attribute on details can group them, so check the support table before writing a script.

Clicking Fees opens its panel and the plus changes to a minus. Clicking it again closes the panel. Each button also works with the keyboard.

Use the simplest tool. If details is enough, use details.

html
<style>
  .acc button { width: 100%; text-align: left; padding: 8px; }
  .acc button[aria-expanded="true"]::after { content: " -"; }
  .acc button[aria-expanded="false"]::after { content: " +"; }
</style>
<div class="acc">
  <h3><button type="button" id="b1" aria-expanded="false" aria-controls="s1">Fees</button></h3>
  <div id="s1" hidden>Pay monthly.</div>
  <h3><button type="button" id="b2" aria-expanded="false" aria-controls="s2">Refunds</button></h3>
  <div id="s2" hidden>Within 7 days.</div>
</div>
<script>
  document.querySelectorAll(".acc button").forEach(b => b.addEventListener("click", () => {
    const open = b.getAttribute("aria-expanded") === "true";
    b.setAttribute("aria-expanded", String(!open));
    document.getElementById(b.getAttribute("aria-controls")).hidden = open;
  }));
</script>

Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Use a heading with a real button inside.
  • aria-expanded holds the state.
  • The hidden attribute hides the closed panel.
  • CSS can read aria-expanded for icons.
  • details is simpler when it is enough.

Common mistakes

  • Using a div or span as the header, which has no keyboard support.
  • Hiding the panel with CSS only but leaving aria-expanded unchanged.
  • Building a custom accordion where details would do.

Follow-ups

  • Why put the button inside a heading?
  • How would you allow only one panel open at a time?

Tips

  • Say the three parts: heading, button, hidden panel.
  • Compare with details and say when each fits.
129.html-css-0129Hardsenior

Build a tooltip that works for mouse and keyboard users. What do the accessibility rules require?

Show the tooltip on hover and keyboard focus, keep it open while the pointer is on it, let Escape dismiss it and keep it until the user moves away. Give it role tooltip and connect it with aria-describedby, and do not put essential or interactive content in it.

Full answer

A tooltip is a small box with extra text for a control, such as an icon button. A good one follows three rules from the accessibility guidelines for content that appears on hover or focus.

  • Dismissible: the user can hide it without moving the pointer or focus, usually with the Escape key.
  • Hoverable: the user can move the pointer onto the tooltip without it disappearing, so that people who zoom in can read it.
  • Persistent: it stays until the user moves away, dismisses it or the information is no longer valid. It must not vanish on a timer.

It must also be reachable by keyboard. Show it on :hover and on :focus-visible (or :focus-within) of the trigger.

Structure:

  • The trigger is a real button or link. Do not make a tooltip for a non-interactive element, because keyboard users cannot reach it.
  • The tooltip element has role="tooltip" and an id. The trigger points to it with aria-describedby, so a screen reader reads the text as a description after the name.
  • The trigger still needs its own accessible name, such as text or aria-label. A tooltip is a description, not a name.
  • Do not put links, buttons or long text in a tooltip. For richer content use a popover or a dialog.

To keep the tooltip open while the pointer moves from trigger to tooltip, make the tooltip a child of a wrapper and show it on .wrap:hover. The wrapper covers both, and a small gap is bridged with padding.

Hovering or focusing the button shows the tooltip. Moving the pointer down onto the tooltip keeps it visible, because it is inside the wrapper. Pressing Escape hides it until the pointer or focus leaves.

Touch screens have no hover, so do not hide essential information in a tooltip.

html
<style>
  .wrap { position: relative; display: inline-block; }
  .tip { position: absolute; left: 0; top: 100%; padding-top: 4px; display: none; }
  .tip span { display: block; background: #222; color: #fff; padding: 4px 8px; font: 14px sans-serif; }
  .wrap:hover .tip, .wrap:focus-within .tip { display: block; }
  .wrap.dismissed .tip { display: none; }
</style>
<div class="wrap" id="w">
  <button type="button" id="b" aria-describedby="tip" aria-label="Help">?</button>
  <div class="tip" id="tipbox"><span role="tooltip" id="tip">Pay by the 5th of each month.</span></div>
</div>
<script>
  w.addEventListener("keydown", e => { if (e.key === "Escape") w.classList.add("dismissed"); });
  for (const ev of ["mouseleave", "focusout"]) w.addEventListener(ev, () => w.classList.remove("dismissed"));
</script>

Checked with mouse hover and real key presses in Chrome. No screen reader was run, and touch was not tested. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Show on hover and on focus.
  • Dismissible with Escape, hoverable and persistent.
  • role=tooltip with aria-describedby on the trigger.
  • The trigger needs its own accessible name.
  • No essential or interactive content in a tooltip.

Common mistakes

  • Using the title attribute as the only tooltip, which keyboard and touch users usually cannot reach.
  • Hiding the tooltip when the pointer leaves the trigger, so it cannot be hovered.
  • Putting essential instructions only in a tooltip.

Follow-ups

  • Why is the title attribute a poor tooltip?
  • When should you use a popover instead?

Tips

  • Name the three requirements: dismissible, hoverable, persistent.
  • Say that aria-describedby gives a description and the control still needs a name.
130.html-css-0130Easyfresher

Cards in a row have different amounts of text. How do you make them the same height?

A flex row stretches its items to equal height by default, so keep align-items at stretch and do not set fixed heights. Make each card a flex column and push the button down with margin-top: auto. Use grid auto-fill for equal widths on every row.

Full answer

In a flex row, items stretch to the height of the tallest item by default. The property align-items has the initial value stretch, so cards are already equal in height, as long as no one has set align-items to another value and the cards have no fixed height. If cards are not equal, check for align-items: flex-start or center, a fixed height on the card, or cards that sit in different rows because they wrapped.

Steps for a neat card row:

  1. Put the cards in a flex container with display: flex; gap: 16px; flex-wrap: wrap;.
  2. Give each card flex: 1 1 200px. This means it can grow, can shrink, and starts at 200px. On a narrow screen the row wraps.
  3. Make each card a flex column, display: flex; flex-direction: column, so that its inner parts can be spread out.
  4. Push the last part, such as a button, to the bottom with margin-top: auto. Then the buttons line up at the bottom of all cards.

On the last wrapped row, a flex card grows to fill the row, so it may be wider than the rest. If you need equal widths on every row, use grid with repeat(auto-fill, minmax(200px, 1fr)) instead.

Do not set a fixed height on cards to make them equal. It cuts off content when the text grows, or when the user increases the font size.

All three cards have the same height, because they stretch. The buttons sit at the bottom of every card, on one line.

Check the cards with longer text and with a larger browser font size.

html
<style>
  .row { display: flex; gap: 16px; width: 700px; }
  .card { flex: 1 1 200px; display: flex; flex-direction: column; border: 1px solid #999; padding: 8px; font: 16px sans-serif; }
  .card button { margin-top: auto; }
</style>
<div class="row">
  <div class="card" id="a"><h3>Short</h3><p>One line.</p><button id="ba">Join</button></div>
  <div class="card" id="b"><h3>Long text</h3><p>This card has much more text so that it takes many lines inside a card which is two hundred pixels wide.</p><button id="bb">Join</button></div>
  <div class="card" id="c"><h3>Medium</h3><p>Two lines of text here.</p><button id="bc">Join</button></div>
</div>

Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • align-items defaults to stretch.
  • Fixed heights and other align-items values break equal heights.
  • Card as a flex column, button with margin-top: auto.
  • flex: 1 1 200px lets cards wrap.
  • Grid gives equal widths on every row.

Common mistakes

  • Setting a fixed height on cards.
  • Setting align-items: flex-start and then wondering why heights differ.
  • Forgetting margin-top: auto, so buttons sit at different heights.

Follow-ups

  • What is the default value of align-items?
  • How do you keep equal widths on the last row?

Tips

  • Say that stretch is the default, and explain what can break it.
  • Add margin-top: auto for the aligned buttons.
131.html-css-0131Mediummid

How can you make a masonry-style layout of different-height cards with CSS columns, and what is the catch?

Use column-width or column-count with column-gap and break-inside: avoid on each card. Items fill each column from top to bottom, so the reading and focus order is not left to right, which makes it unsuitable for ordered content.

Full answer

CSS multi-column layout splits content into columns like a newspaper. With it, a masonry look needs very little code.

  • column-count: 3 sets the number of columns. column-width: 200px instead lets the browser fit as many columns of at least that width as possible, which is responsive without media queries.
  • column-gap sets the space between columns.
  • Items flow down the first column, then the next one. To keep a card whole, set break-inside: avoid on each card. Without it, a card can be split between two columns.
  • Cards need a bottom margin to space them, since gap only works between columns.

The catch is the order. Items go top to bottom in the first column, then continue at the top of the second column. A grid of photos that should read left to right will be in a different order than the visitor expects, and keyboard focus follows the same order, so Tab moves down a column and then up to the next. For content where the order matters, such as search results or steps, this layout is a poor choice. It suits independent items such as a photo wall or notes.

Other facts:

  • A tall item cannot span columns, except with column-span: all, which spans every column.
  • The column heights are balanced by the browser.
  • CSS Grid and Flexbox give you a left-to-right order, but not a true masonry layout by themselves. A native masonry feature for grid is still new, so check the support table before using it. JavaScript libraries can place cards by measuring them, at some cost to speed and complexity.

With 400px and a 120px column width, there are three columns. The browser balances their heights: cards 1 and 2 are stacked in the first column, card 3 is alone in the second, and cards 4 and 5 are stacked in the third. The reading order goes down each column, not across.

Pick this layout only when the order of items does not matter.

html
<style>
  .wall { column-width: 120px; column-gap: 12px; width: 400px; }
  .card { break-inside: avoid; margin: 0 0 12px; padding: 8px; background: #eef; font: 14px sans-serif; }
</style>
<div class="wall" id="wall">
  <div class="card" id="c1" style="height:80px">1</div>
  <div class="card" id="c2" style="height:40px">2</div>
  <div class="card" id="c3" style="height:100px">3</div>
  <div class="card" id="c4" style="height:50px">4</div>
  <div class="card" id="c5" style="height:60px">5</div>
</div>

Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • column-count or column-width creates columns.
  • break-inside: avoid keeps a card whole.
  • Spacing inside a column needs margins.
  • Order runs down each column, not across.
  • Native grid masonry is new; check support.

Common mistakes

  • Using columns for content that has a meaningful left-to-right order.
  • Forgetting break-inside: avoid, so cards are cut across columns.
  • Expecting row-gap or gap to space items inside a column.

Follow-ups

  • Why does keyboard order matter here?
  • How does column-width differ from column-count?

Tips

  • Say that columns make a masonry look easily, then state the order problem.
  • Mention that native masonry for grid is new, with the support caveat.
132.html-css-0132Easyfresher

What do the lang and dir attributes do, and why do they matter beyond looks?

lang names the language so screen readers, spell checkers, hyphenation, translation and search work correctly, and it can be set on a single phrase. dir sets the text direction, and rtl mirrors the flow for languages such as Arabic and Hebrew.

Full answer

The lang attribute on the html element names the main language of the page, such as lang="en" or lang="hi". It looks small, but many tools use it.

  • Screen readers choose the right voice and pronunciation. Without it, English text can be read with the wrong accent, or in a voice that makes no sense.
  • Browsers choose the right quotation marks, hyphenation rules and fonts for the script. hyphens: auto works only when the language is known.
  • Translation tools and search engines use it to detect the language. Spell checkers use it too.
  • CSS can select by language with :lang(fr).

For a short phrase in another language, put lang on that element only: <span lang="fr">bonjour</span>. Then a screen reader switches voice for those words.

The dir attribute sets the text direction: ltr, rtl or auto. Languages such as Arabic and Hebrew run right to left. Set dir="rtl" on the html element (or on a part of the page) for such pages, and the browser mirrors the text flow, the alignment, the scrollbar side and the order of flex and grid items. dir="auto" lets the browser look at the first strong character, which is useful for user-generated text. If you use logical CSS properties such as margin-inline-start, your styles follow the direction without extra rules.

Use language codes from the standard, such as en, en-GB, pt-BR, zh-Hans. Keep the code short and correct.

The French word is italic because of the :lang(fr) rule, and a screen reader can read it with a French voice. The Arabic paragraph is aligned to the right. The last paragraph has dir="auto", so Hebrew text is treated as right to left without more code.

Set the language on every page, because it is a basic accessibility requirement.

html
<!DOCTYPE html>
<html lang="en" id="root">
<head><meta charset="utf-8"><title>Language</title></head>
<body>
  <p id="p1">The word <span lang="fr" id="fr">bonjour</span> is French.</p>
  <p lang="ar" dir="rtl" id="ar" style="text-align:start;width:300px">مرحبا</p>
  <p id="p3" dir="auto" style="width:300px;text-align:start">שלום</p>
  <style>:lang(fr) { font-style: italic; }</style>
</body>
</html>

This is a complete page, because the lang attribute sits on the html element. Without the doctype the page runs in quirks mode.

Key points

  • Put lang on the html element on every page.
  • Use lang on a phrase to switch language.
  • dir sets ltr, rtl or auto.
  • Logical properties follow the direction.
  • Use correct standard language codes.

Common mistakes

  • Leaving out lang on the html element.
  • Using a wrong code, such as lang="english".
  • Flipping a layout with transforms for right-to-left languages instead of using dir and logical properties.

Follow-ups

  • What does dir="auto" do?
  • How do logical properties help with dir?

Tips

  • Name screen readers, hyphenation and translation as the practical effects.
  • Mention lang on a single phrase.
133.html-css-0133Easyfresher

Which small text-level elements such as time, abbr, mark, kbd and address do you use, and what do they add?

Text-level elements add meaning: time with a datetime value, abbr with the full form, mark for relevant text, kbd and code for input and code, address for contact details, and q or blockquote for quotes. Choose by meaning and style with CSS.

Full answer

Text-level elements add meaning to a few words inside a paragraph. They help assistive tools, search engines and browser features, and they have useful default styles.

  • time marks a date or time. The datetime attribute holds a machine-readable value, such as 2026-12-04 or 2026-12-04T10:30, while the text can be anything, such as "Friday". Tools can use it for calendars and rich results.
  • abbr marks an abbreviation. The title attribute holds the full form, and browsers draw a dotted underline. A tooltip from title is not reachable by keyboard or touch, so spell the term out at its first use too.
  • mark highlights text that is relevant right now, for example a search match. It is not for plain decoration.
  • kbd marks keys or input the user types, such as Ctrl + S. code marks code, samp marks sample output and var marks a variable. They use a monospace font by default.
  • address gives contact information for the nearest article or for the whole page. It is not for any postal address in the text.
  • q is a short inline quote, and the browser adds quotation marks. blockquote is for long quotes, with cite to name the source.
  • strong shows strong importance and em shows stress in speech. b and i are for style with no extra meaning, such as a product name or a technical term.
  • sup, sub and small are for superscripts, subscripts and fine print such as legal text.

Use the element that matches the meaning, then style it with CSS. Do not use strong just to make text bold, and do not skip the element because you can fake the look.

The time element carries a precise value for tools. The keys use a monospace font, the abbreviation has a dotted underline and the match has a yellow background by default. The address is shown in italics in most browsers.

Choose by meaning, and check the default styles for your design.

html
<p>The event is on <time id="t" datetime="2026-12-04T10:30">Friday morning</time>.
Press <kbd id="k">Ctrl</kbd> + <kbd>S</kbd> to save.
<abbr id="a" title="HyperText Markup Language">HTML</abbr> is simple.
Search result: <mark id="m">flexbox</mark> guide.</p>
<address id="ad">Write to <a href="mailto:hello@example.com">hello@example.com</a></address>

Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • time holds a machine-readable date in datetime.
  • abbr gives the full form, but spell it out too.
  • mark highlights relevant text.
  • kbd, code and samp mark input, code and output.
  • Choose by meaning, not by default look.

Common mistakes

  • Using strong or em only to change how text looks.
  • Relying on the abbr title as the only place where the full form appears.
  • Using address for any postal address inside an article.

Follow-ups

  • What is the difference between strong and b?
  • Why is the datetime attribute useful?

Tips

  • Pick three or four elements and say what each means.
  • Say that the choice is by meaning, and styles come second.
134.html-css-0134Easyfresher

How do you mark up an image with a caption and a quotation correctly?

A figure wraps self-contained content such as an image, and figcaption gives it a visible caption. The caption does not replace alt text, which describes the image for people who cannot see it. A blockquote marks a long quotation, with the source named in visible text.

Full answer

Use figure for self-contained content that is referred to from the text and could move elsewhere without breaking the sense: an image, a chart, a code sample, a quote. figcaption gives it a caption, and it must be the first or the last child of the figure.

The figcaption also gives the figure an accessible name in many browsers, so assistive tools can announce "figure, Students at the gate".

A caption is not the same as alt text.

  • alt replaces the image for people who cannot see it. It describes what the image shows or what it is for.
  • figcaption is visible text for everyone. It adds context, such as a source or a date. If the caption already describes the image fully, the alt can be short, but it should not be left out unless the image is decorative. Do not repeat the same sentence in both, because screen reader users hear it twice.

For quotes:

  • blockquote holds a longer quotation taken from another source. The optional cite attribute gives the address of the source. It is not shown by browsers, so name the source in visible text as well.
  • Put the attribution in a figcaption inside a figure around the blockquote, with the source in a cite element, which is used for the title of the work.
  • q is for a short quote inside a sentence.

Do not use blockquote just to indent text, since it carries the meaning of a quotation.

Each figure groups its content with its caption. The image keeps a short, useful alt, and the quote gets its source in a visible caption. The default style of a figure adds side margins, which you can reset in CSS.

Check with a screen reader that the caption and the alt text do not repeat each other.

html
<figure id="f1">
  <img src="/img/gate.jpg" alt="Students walking through a stone gate" width="300" height="200">
  <figcaption>Students at the gate, 2026.</figcaption>
</figure>
<figure id="f2">
  <blockquote cite="https://example.com/talk"><p>Make it work, then make it fast.</p></blockquote>
  <figcaption>Speaker name, <cite>Talk title</cite></figcaption>
</figure>

Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • figure groups self-contained content; figcaption is its caption.
  • figcaption must be the first or last child.
  • alt and figcaption have different jobs.
  • blockquote is for quotations, not indentation.
  • Name the source in visible text.

Common mistakes

  • Using figure for every image, even when it is just a decoration or a part of the page layout.
  • Copying the caption into the alt attribute.
  • Using blockquote only to indent text.

Follow-ups

  • Where can figcaption go inside a figure?
  • What does the cite attribute on blockquote do?

Tips

  • Explain figure as a self-contained unit with an optional caption.
  • State the difference between alt and figcaption.
135.html-css-0135Mediummid

How does @supports work, and how do you use it to add a modern feature with a safe fallback?

@supports applies rules only if the browser understands a property, a value or a selector. Write a working fallback first, then override it inside @supports. For a single declaration, the old value first and the new one after it often works without a query.

Full answer

@supports is a feature query. It applies the rules inside it only if the browser understands the condition, so you can use a new feature without breaking older browsers.

Forms of the condition:

  • @supports (display: grid) { ... } is true when the browser knows the property and the value.
  • @supports not (display: grid) { ... } is true when it does not. Use it for fallback rules only when you cannot arrange the fallback first.
  • and, or and brackets combine conditions: @supports (display: grid) and (gap: 1rem).
  • @supports selector(:has(a)) { ... } tests selector support.

The best pattern is progressive enhancement. First write the simple rules that work everywhere, the fallback. Then, inside @supports, write the modern version, which overrides the fallback in browsers that understand it. Older browsers skip the block and keep the fallback.

Many features need no @supports. If a browser does not understand a declaration, it ignores that single declaration, so writing the old value first and the new one after it is enough. Use @supports when:

  • You must change several rules together, such as turning on a new layout and changing the child rules too.
  • A rule is only safe when the feature exists. For example, position: sticky or a grid layout needs matching changes on the children.
  • The browser understands the property name but the value would cause a worse result than the fallback.

From JavaScript, CSS.supports("display", "grid") runs the same test.

The cards use the grid version in this browser, so they sit in two columns. The nonsense feature is not supported, so the red outline is never applied. The paragraph that contains a link turns green because the browser understands :has().

Test the fallback too, for example by editing the condition to something false.

html
<style>
  .cards { display: flex; flex-wrap: wrap; gap: 8px; width: 400px; }
  .cards > div { flex: 1 1 100px; background: #cde; padding: 4px; }
  @supports (display: grid) {
    .cards { display: grid; grid-template-columns: repeat(2, 1fr); }
  }
  @supports (foo: bar) { .cards { outline: 3px solid red; } }
  .tag { color: black; }
  @supports selector(:has(a)) { .tag:has(a) { color: green; } }
</style>
<div class="cards" id="c"><div>1</div><div>2</div><div>3</div></div>
<p class="tag" id="t"><a href="#">link</a></p>

Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • @supports tests properties, values and selector().
  • Fallback first, enhancement inside the query.
  • Unknown declarations are ignored anyway.
  • Use it when several rules must change together.
  • CSS.supports() tests from JavaScript.

Common mistakes

  • Writing the modern version first and having no fallback.
  • Using @supports for single declarations where writing the old value first is enough.
  • Never testing the fallback path.

Follow-ups

  • What does @supports not do?
  • How can JavaScript test for CSS support?

Tips

  • Describe progressive enhancement: fallback first, enhancement inside @supports.
  • Say that unknown declarations are ignored, so @supports is not always needed.
136.html-css-0136Easyfresher

What are good ways to space a vertical stack of elements, and why do people avoid margin on every item?

Space a stack from the container: use gap on a flex or grid container, or the owl selector > * + * in normal flow. Both add space only between items, so there is none at the ends, and they avoid per-item margins and the last-child fix.

Full answer

A stack is a list of blocks, one under another, with an equal space between them. There are three common ways to make the space.

  • Margin on every item, such as margin-bottom: 16px. The last item also gets a space after it, so the container has extra space at the bottom. People often add :last-child { margin-bottom: 0 } to remove it. Margins can also collapse, which can give surprising results.
  • The "owl" selector: .stack > * + * { margin-block-start: 16px; }. It adds space only between items, so there is no extra space at the start or the end. It works for any item, even when items are added later. Use :where() to give it zero specificity, so components can still change their own margin.
  • display: flex; flex-direction: column; gap: 16px or display: grid; gap: 16px. The gap property exists only between items, so it gives the same result with one line and no selector tricks. Margins on flex and grid items do not collapse. This is the simplest choice today.

Which to use?

  • Use gap when the container can be a flex or grid container. This is common for components.
  • Use the owl selector for normal flow, such as article text, where you do not want to change the display type, and where paragraphs should keep collapsing margins and normal inline behaviour.

Space belongs to the container and not to the items. If the items own their margins, moving an item to another place brings its old spacing along, and the layout breaks.

Both stacks have the same height: three boxes of 20px and two gaps of 16px, which is 92px. Neither has extra space before the first box or after the last one.

Pick one method for a whole project, so spacing is predictable.

html
<style>
  .stack-owl > *, .stack-gap > * { height: 20px; background: #cde; }
  :where(.stack-owl) > * + * { margin-block-start: 16px; }
  .stack-gap { display: grid; gap: 16px; }
</style>
<div class="stack-owl" id="o"><div>1</div><div>2</div><div>3</div></div>
<div class="stack-gap" id="g"><div>1</div><div>2</div><div>3</div></div>

Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Per-item margins leave extra space at the end.
  • The owl selector adds space only between siblings.
  • gap on flex or grid does the same in one line.
  • Flex and grid margins do not collapse.
  • Space belongs to the container.

Common mistakes

  • Putting margin-bottom on every item and getting extra space at the end.
  • Mixing gap, owl selectors and margins in one component.
  • Letting an item keep its own spacing, so it looks wrong when moved elsewhere.

Follow-ups

  • Why does the owl selector use > * + *?
  • Do margins collapse between flex items?

Tips

  • Compare the three options and say which you prefer and why.
  • Mention that space belongs to the container.
137.html-css-0137Easyfresher

How do you put a small notification badge on the corner of an avatar or an icon?

Make the wrapper position: relative and the badge position: absolute at top: 0 and right: 0. Add transform: translate(50%, -50%) to centre it on the corner, and give it hidden text that a screen reader can read.

Full answer

This is a standard use of absolute positioning inside a relative parent.

  1. The wrapper gets position: relative. It becomes the reference box for the badge. The wrapper should fit the avatar, so make it display: inline-block, or a flex or grid item that does not stretch.
  2. The badge gets position: absolute with top: 0 and right: 0. That puts its top-right corner at the corner of the wrapper.
  3. To centre the badge on the corner instead, move it by half of its own size with transform: translate(50%, -50%). Percentages in translate are percentages of the element itself, so this works for any badge size, even when the number inside gets wider.

Other points:

  • The badge needs min-width and a rounded shape, with padding that fits the text, and a border in the page colour so it stands out from the avatar.
  • Add accessible text. A number alone, such as "3", has no meaning for a screen reader. Add visually hidden text, such as "3 new messages", or give the control a label that includes the count. Hide the visible number with aria-hidden if the hidden text already says it.
  • If the wrapper is a button, the badge belongs inside the button so it is part of the same control.
  • Do not use float or manual margins to place a badge. They break when the text changes.

The red badge sits with its centre on the top-right corner of the avatar image. When the number grows to two digits, the badge grows to the left and right by the same amount, because the translate uses half of its own width.

Check with a longer number such as 99+ and with a larger browser font size.

html
<style>
  .avatar { position: relative; display: inline-block; margin: 20px; }
  .avatar img { display: block; width: 48px; height: 48px; border-radius: 50%; background: #ccc; }
  .badge { position: absolute; top: 0; right: 0; transform: translate(50%, -50%);
    min-width: 20px; height: 20px; padding: 0 4px; box-sizing: border-box;
    border-radius: 10px; background: #c00; color: #fff; font: 12px/20px sans-serif; text-align: center; }
</style>
<span class="avatar" id="a">
  <img src="/img/user.png" alt="Asha">
  <span class="badge" id="b"><span aria-hidden="true">3</span><span style="position:absolute;left:-9999px">3 new messages</span></span>
</span>

Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • The wrapper needs position: relative and a size that fits the avatar.
  • The badge uses position: absolute with top and right.
  • translate(50%, -50%) centres it on the corner at any size.
  • Add a border so it stands out.
  • Add accessible text for the count.

Common mistakes

  • Forgetting position: relative on the wrapper, so the badge goes to the page corner.
  • Using a fixed left margin to place the badge, which breaks when the number grows.
  • Showing only a number with no text for screen readers.

Follow-ups

  • Why do percentages in translate use the element's own size?
  • How would you make the count readable for a screen reader?

Tips

  • Describe the pair: relative parent, absolute child.
  • Explain why translate(50%, -50%) centres the badge on the corner.
138.html-css-0138Mediummid

How do text-wrap, overflow-wrap and hyphens control how text breaks into lines?

text-wrap: balance evens out lines in short headings, pretty improves paragraph breaks, overflow-wrap breaks long strings, and hyphens: auto adds hyphens using the language dictionary. text-wrap is newer, and older browsers just use normal breaks.

Full answer

Different properties solve different line-breaking problems.

  • text-wrap: balance asks the browser to make the lines of a short block about equal in length. It is meant for headings and captions, up to a few lines, because it is costly for long text. A heading is then not left with one lonely word on the last line.
  • text-wrap: pretty asks for better line breaks in paragraphs, for example avoiding a very short last line. It is a hint, and the exact result depends on the browser.
  • overflow-wrap: break-word (or anywhere) lets a very long word break so it does not overflow the box. It matters for URLs and user-generated text. The difference between the two is in how min-content size is computed: anywhere lets the long word count as small in the intrinsic size, which helps inside flex and grid items, while break-word does not.
  • word-break: break-all breaks anywhere, even in normal words. It is rarely wanted for English text.
  • hyphens: auto lets the browser add hyphens at correct places in a word. It needs a correct lang attribute, because the dictionary depends on the language. hyphens: manual uses only the soft hyphens (&shy;) that you add yourself.
  • white-space: nowrap stops all wrapping, and text-overflow: ellipsis can then cut the line.

text-wrap is a newer property. Check the support table. Browsers that do not know it simply use the normal breaks, which is an acceptable fallback.

The two headings have the same text and the same width. The balanced one has lines that are closer in length, so its last line is wider than the plain one. The long address wraps inside its 120px box. The hyphenated word may break with a hyphen where the browser has a dictionary for English.

Hyphenation depends on the browser and the language data, so test it on your target browsers.

html
<style>
  .box { width: 220px; font: 20px/1.3 sans-serif; background: #eef; margin: 8px 0; }
  .balance { text-wrap: balance; }
  .url { width: 120px; overflow-wrap: anywhere; background: #fee; }
  .hy { width: 90px; hyphens: auto; }
</style>
<h2 class="box" id="plain" style="margin:0">Write clean HTML and style it with simple CSS rules</h2>
<h2 class="box balance" id="bal" style="margin:0">Write clean HTML and style it with simple CSS rules</h2>
<div class="url" id="u">https://example.com/a/very/long/address/without/breaks</div>
<p class="box hy" id="h" lang="en">Internationalization</p>

Checked in Chrome 156 only. The balanced heading had a last line much wider than the plain one. Hyphenation depends on the browser and was only checked as a computed value. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • balance is for headings and short blocks.
  • pretty is a hint for better paragraph breaks.
  • overflow-wrap handles long URLs and words.
  • hyphens: auto needs a correct lang.
  • Check support for text-wrap.

Common mistakes

  • Using word-break: break-all for normal text.
  • Using text-wrap: balance on a long paragraph.
  • Using hyphens: auto without a lang attribute.

Follow-ups

  • What is the difference between overflow-wrap: anywhere and break-word?
  • Why does hyphens: auto need lang?

Tips

  • Match each property to its problem: lonely last word, long URL, long word hyphenation.
  • Say that balance is for short blocks only.
139.html-css-0139Mediummid

How do you stop hover effects from sticking on touch screens, and make targets larger for touch?

Wrap hover effects in @media (hover: hover) so they do not stick on touch screens, and use @media (pointer: coarse) to enlarge targets. Never hide essential actions behind hover, and remember that some devices have both a mouse and touch.

Full answer

On a touch screen there is no pointer to hover with. Many phones fake it: after a tap, the element keeps the :hover style until the user taps somewhere else. A menu or button can look stuck in its hover state. Also, a menu that opens only on hover cannot be opened by touch.

Interaction media features let CSS ask what the device can do:

  • (hover: hover) is true when the main input can hover, such as a mouse. (hover: none) is true for a typical touch screen.
  • (pointer: fine) means a precise pointer such as a mouse. (pointer: coarse) means a finger or a similar low-precision input.
  • any-hover and any-pointer check all inputs, not only the main one. A laptop with a touch screen has both. Do not treat the device as one or the other. Use the primary input features for style, and let the other controls still work.

Rules of thumb:

  1. Wrap hover-only effects in @media (hover: hover) { ... }, so they apply only where hover exists.
  2. Never hide important content or actions behind hover. Everything must also work with focus and tap.
  3. For pointer: coarse, make targets bigger: about 44 by 44 CSS pixels is a common guideline, with space between them.
  4. Show focus styles with :focus-visible for keyboard users in every case.

These checks give hints about input, not certainty, so keep the page usable without them.

In a desktop browser, the button turns blue on hover and keeps its small size. On a phone, the hover rule is not used, so there is no stuck blue state, and the button is at least 44px high.

The check here ran with a mouse only. The coarse pointer rule was not run on a touch device, so test on a phone or with device emulation.

html
<style>
  .btn { padding: 4px 8px; min-height: 24px; background: #eee; border: 1px solid #999; }
  @media (hover: hover) { .btn:hover { background: #cde; } }
  @media (pointer: coarse) { .btn { min-height: 44px; padding: 12px 16px; } }
</style>
<button class="btn" id="b" type="button">Add</button>

The check ran with a mouse only. The rule for a coarse pointer was not run on a touch device. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Touch devices can leave :hover stuck after a tap.
  • @media (hover: hover) limits hover styles to devices that can hover.
  • pointer: coarse signals finger input; make targets large.
  • any-hover and any-pointer check all inputs.
  • Do not hide essential content behind hover.

Common mistakes

  • Showing menus or essential actions only on :hover.
  • Assuming a screen with touch has no mouse and removing hover styles for it.
  • Making small touch targets with no space between them.

Follow-ups

  • What is the difference between hover and any-hover?
  • What size should touch targets be?

Tips

  • Explain the sticky hover problem on touch screens in one sentence.
  • Name hover and pointer, and the any- versions.
140.html-css-0140Hardsenior

A CSS-only dropdown menu opens on hover. What accessibility problems does it have, and how do you improve it?

A hover-only dropdown fails for keyboard, touch and screen reader users and cannot be dismissed. Use a button with aria-expanded that toggles the menu, close it on Escape and when focus leaves, return focus to the button, and consider whether a dropdown is needed.

Full answer

A common CSS-only dropdown is a list of links inside a wrapper, hidden until .wrap:hover. It works with a mouse and fails in many other cases.

Problems:

  • Keyboard users cannot open it. Hover does not happen with Tab. Adding :focus-within fixes the opening part: the menu shows while any element inside the wrapper has focus. If the menu uses display: none, the links inside cannot be focused at all. Then the trigger has to be a button that is focusable, and the menu opens when the button has focus.
  • Touch users have no hover. A tap on the button should toggle the menu, so a script is needed.
  • No Escape key. The guidelines ask for hidden-on-hover content to be dismissible.
  • No state for screen readers. A button needs aria-expanded that reflects the open state, which CSS alone cannot update.
  • The pointer gap. A gap between the trigger and the menu closes the menu as the pointer crosses it. Make the menu touch the trigger, or bridge the gap with padding.

An improved approach keeps CSS for the look and adds a few lines of script:

  1. A real button with aria-expanded and aria-controls toggles the menu on click, and on Enter and Space.
  2. The menu is hidden with the hidden attribute (or display: none) when closed.
  3. Escape closes it and returns focus to the button.
  4. Clicking outside, or moving focus out of the wrapper, closes it.
  5. Optionally open on hover with @media (hover: hover) as an extra.

For site navigation, a simple list of links that always stays open on small screens is often better than a dropdown.

Clicking or pressing Enter on the button opens the list. Tab moves into the links. Escape closes the list and returns focus to the button. Moving focus out of the wrapper closes it.

Test with a keyboard, a touch screen and a screen reader before shipping navigation like this.

html
<style>
  .wrap { position: relative; display: inline-block; }
  .menu { position: absolute; top: 100%; left: 0; margin: 0; padding: 0; list-style: none; background: #eee; }
  .menu[hidden] { display: none; }
  .menu a { display: block; padding: 6px 12px; }
</style>
<div class="wrap" id="w">
  <button type="button" id="btn" aria-expanded="false" aria-controls="m">Courses</button>
  <ul class="menu" id="m" hidden>
    <li><a href="#html" id="l1">HTML</a></li>
    <li><a href="#css">CSS</a></li>
  </ul>
</div>
<script>
  function setOpen(o) { btn.setAttribute("aria-expanded", o); m.hidden = !o; }
  btn.addEventListener("click", () => setOpen(btn.getAttribute("aria-expanded") !== "true"));
  w.addEventListener("keydown", e => { if (e.key === "Escape") { setOpen(false); btn.focus(); } });
  w.addEventListener("focusout", e => { if (!w.contains(e.relatedTarget)) setOpen(false); });
</script>

Checked with mouse clicks and real key presses in Chrome. No screen reader was run, and touch was not tested. Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.

Key points

  • Hover does not work with keyboard or touch.
  • :focus-within cannot reach links hidden with display: none.
  • Use a button with aria-expanded and aria-controls.
  • Escape and focus-out should close the menu.
  • Avoid pointer gaps between trigger and menu.

Common mistakes

  • Opening a menu only on :hover.
  • Using display: none and :focus-within and expecting hidden links to receive focus.
  • Leaving a gap between the trigger and the menu so the menu closes as the pointer crosses it.

Follow-ups

  • Why can :focus-within not open a menu hidden with display: none?
  • When is a dropdown not needed at all?

Tips

  • List the missing pieces: keyboard, touch, Escape, state, pointer gap.
  • Say that a button with aria-expanded is the base of the fix.