PrepStack › Frontend › HTML & Accessibility

HTML & Accessibility interview cheat sheet

Semantic markup, forms, media, loading, SEO, WCAG, ARIA and keyboard support

HTML questions look easy, but interviewers use them to see whether you write markup that browsers, search engines and assistive tech understand. Expect questions on semantic elements, forms, images, async vs defer, then a deeper accessibility round: WCAG, ARIA rules, accessible names, focus management, live regions and modals. Read the 15-minute revision first, then switch to Quiz mode and answer out loud.

15-minute revision

  1. Always start with <!DOCTYPE html>. Without it the browser falls back to quirks mode and old layout rules.
  2. Put <meta charset="utf-8"> first in <head>, add <meta name="viewport" content="width=device-width, initial-scale=1">, and set <html lang="en"> so screen readers use the right voice.
  3. Use semantic elements (header nav main article section aside footer) instead of div soup. They give free landmarks, better SEO and keyboard behaviour.
  4. Every form control needs a label: <label for="id"> or a wrapping label. A placeholder is not a label.
  5. <button> inside a form defaults to type="submit". Set type="button" for non-submit buttons.
  6. alt text: describe the purpose of meaningful images; use alt="" for decorative ones. Never leave alt out.
  7. srcset + sizes let the browser pick a resolution; <picture> is for art direction or new formats (AVIF/WebP). Do not lazy-load the LCP image.
  8. defer runs scripts in order after parsing; async runs each one as soon as it downloads, in any order. type="module" is deferred by default.
  9. WCAG = POUR (Perceivable, Operable, Understandable, Robust) with levels A, AA, AAA. Current version is 2.2; AA is the usual legal target.
  10. First rule of ARIA: use a native element if one exists. No ARIA is better than bad ARIA.
  11. aria-labelledby beats aria-label beats native label in the name calculation. aria-describedby adds extra help text, not the name.
  12. tabindex="0" adds an element to tab order, -1 makes it focusable only by script, positive values break the natural order: avoid them.
  13. Contrast: 4.5:1 for normal text, 3:1 for large text and for UI parts and focus indicators (AA).
  14. Live regions (aria-live="polite", role="status", role="alert") announce dynamic updates. The region must exist before you change its text.
  15. Modals: use <dialog> with showModal(). It traps focus, makes the page inert and closes on Esc. Return focus to the opener.
  16. Automated tools (axe, Lighthouse) find only part of the problems. Always add a keyboard-only pass and a screen-reader pass.

Document & core HTML

Document structure & doctype

A valid page is a doctype, then <html lang> with one <head> (metadata) and one <body> (content).

  • <!DOCTYPE html> is not a tag. It tells the browser to use standards mode. Missing it triggers quirks mode, which emulates old browser bugs (for example the box model).
  • <html lang="en"> sets the page language. Screen readers pick pronunciation from it, and browsers use it for hyphenation and translation. Use lang on parts in another language.
  • <head> holds metadata that is not shown: charset, title, meta tags, links to CSS, scripts, icons.
  • <body> holds the visible content. There is exactly one of each.
  • The browser is forgiving: it fixes bad markup while building the DOM. Valid HTML still matters because error recovery can produce a tree you did not expect.
  • HTML is a living standard maintained by WHATWG. There is no "HTML6"; "HTML5" today just means modern HTML.

Interview questions

  • What does <!DOCTYPE html> do?
  • Why set the lang attribute?
  • What happens when the browser meets invalid HTML?

Head & meta tags (charset, viewport, OG)

The head controls encoding, mobile scaling, the tab title, search snippets and social share cards.

  • <meta charset="utf-8"> must appear within the first 1024 bytes so the parser decodes text correctly from the start.
  • <meta name="viewport" content="width=device-width, initial-scale=1"> makes mobile browsers use the device width instead of a ~980px fake desktop width.
  • Do not add user-scalable=no or maximum-scale=1. Blocking zoom fails WCAG 1.4.4 (Resize Text).
  • <title> is shown in tabs, bookmarks and search results, and it is the first thing a screen reader announces. Make it unique per page.
  • Open Graph (og:title, og:description, og:image, og:url, og:type) controls link previews on social apps and chat tools. twitter:card sets the X/Twitter card style.
  • Resource hints: rel="preload" (fetch this now), rel="preconnect" (open the connection early), rel="prefetch" (likely needed for the next page), rel="canonical" (the preferred URL).

Interview questions

  • What does the viewport meta tag do?
  • What is Open Graph?
  • Difference between preload, prefetch and preconnect?

Semantic elements, block vs inline

Pick elements by meaning, not looks. Meaning gives landmarks, keyboard behaviour and SEO for free; CSS decides the looks.

  • Landmarks: <header> (banner when top-level), <nav>, <main> (one visible per page), <aside> (complementary), <footer> (contentinfo when top-level), <form> and <section> when they have a name.
  • <article> is self-contained content that makes sense on its own (post, card, comment). <section> is a themed part of a page and should have a heading. <div> has no meaning: use it only for styling hooks.
  • Text semantics: <strong> (importance) vs <b> (just bold), <em> (stress) vs <i> (alternate voice, terms). Also <time datetime>, <abbr>, <mark>, <code>, <blockquote>, <figure> + <figcaption>, <address>.
  • Headings <h1>–<h6> form the page outline. Screen-reader users jump by headings, so do not skip levels just for size.
  • Interactive: <button> for actions, <a href> for navigation, <details>/<summary> for disclosure, <dialog> for modals.
  • Block elements start on a new line and take full width (div p h1 ul section). Inline elements flow inside text and ignore width/height (span a strong em). This is just the default CSS display, which you can change.

Interview questions

  • What is semantic HTML and why does it matter?
  • Difference between <section>, <article> and <div>?
  • <b> vs <strong>, <i> vs <em>?
  • Difference between block and inline elements?
  • How many <h1> should a page have?

Forms, tables & media

Forms, input types & labels

Use the right input type, a real label for every control, and group related controls with fieldset/legend.

  • Link a label with <label for="email"> + id="email", or wrap the input inside the label. Clicking the label focuses the input, and screen readers read it as the name.
  • Input types give the right mobile keyboard and free validation: email, tel, url, number, search, password, date, time, datetime-local, month, week, color, range, file, checkbox, radio, hidden.
  • name is the key sent to the server; id is for the label and scripts. Radios with the same name form one group.
  • autocomplete tokens (email, given-name, street-address, one-time-code, new-password) enable autofill and are required by WCAG 1.3.5 for personal data.
  • <fieldset> + <legend> group radios or checkboxes so the question ("Delivery speed") is read with each option.
  • method="get" puts data in the URL (searches, filters). method="post" sends it in the body (anything that changes data or is sensitive).

Interview questions

  • How do you associate a label with an input?
  • Difference between disabled and readonly?
  • Why should a <button> in a form have an explicit type?

Validation & accessible form errors

Use built-in constraints first, the Constraint Validation API for custom rules, and make errors visible, specific and announced.

  • Built-in constraints: required, type, min/max/step, minlength/maxlength, pattern (implicitly anchored to the whole value). The form will not submit while any fails.
  • Each control has a validity object (valueMissing, typeMismatch, patternMismatch, tooShort, rangeOverflow, customError …) plus checkValidity(), reportValidity() and setCustomValidity(msg).
  • novalidate on the form turns off the browser's bubbles so you can show your own messages, while still using the API.
  • :invalid matches immediately on page load; :user-invalid only matches after the user has interacted, which is what you usually want to style.
  • Accessible errors: set aria-invalid="true", link the message with aria-describedby, say what is wrong and how to fix it, and do not rely on red color alone (WCAG 3.3.1, 3.3.3).
  • On submit with many errors, move focus to an error summary at the top with links to each field, or focus the first invalid field.
  • Client validation is for UX only. Always validate again on the server.

Interview questions

  • What is the Constraint Validation API?
  • How do you make form errors accessible?
  • Why validate on the server if the browser already does it?
  • :invalid vs :user-invalid?

Tables

Tables are for tabular data only. Use caption, th and scope so each cell can be read with its headers.

  • Structure: <table> > <caption> > <thead> / <tbody> / <tfoot> > <tr> > <th> / <td>.
  • <caption> is the table's accessible name and visible title.
  • <th scope="col"> and <th scope="row"> tell screen readers which header applies, so moving cell by cell reads "Q2, Revenue, 1.4M".
  • For complex tables with multi-level headers, give headers ids and list them in each cell's headers attribute.
  • colspan and rowspan merge cells. Keep them simple; heavy merging is hard to navigate by ear.
  • Never use tables for page layout. If you must keep an old layout table, add role="presentation".

Interview questions

  • How do you make a data table accessible?
  • Why not use tables for layout?

Images: alt, srcset, sizes, picture, lazy loading

Give every image a correct alt, let the browser choose the right file with srcset/sizes, and reserve space with width/height.

  • alt describes the purpose of the image in context. Decorative images get alt="" so screen readers skip them. If an image is a link, the alt should describe the destination.
  • srcset with w descriptors + sizes lets the browser pick by layout width and pixel density. srcset with x descriptors (1x, 2x) is for fixed-size images.
  • sizes tells the browser how wide the image will be before CSS loads, for example (min-width: 800px) 50vw, 100vw. Without it, the browser assumes 100vw.
  • <picture> + <source>: use type to offer new formats (AVIF, WebP) with a fallback, or media for art direction (a different crop on mobile). The inner <img> is required; it carries alt and is what actually renders.
  • loading="lazy" delays offscreen images. Never lazy-load the LCP hero image; give it fetchpriority="high" instead.
  • Always set width and height (or CSS aspect-ratio) so the browser reserves space and avoids layout shift (CLS).

Interview questions

  • What makes good alt text?
  • Difference between alt="" and no alt?
  • When do you use <picture> instead of srcset?
  • Why set width and height on images in responsive design?
  • Should you lazy-load every image?

Loading, APIs & SEO

Script loading: async vs defer vs module

defer = download in parallel, run in order after parsing. async = download in parallel, run as soon as ready. Modules defer by default.

  • A plain <script src> blocks parsing while it downloads and runs. That is why old advice put scripts at the end of <body>.
  • defer: downloads in parallel, runs after the document is parsed, in document order, before DOMContentLoaded. Best default for app code.
  • async: downloads in parallel, runs as soon as it arrives, pausing the parser at that moment. Order is not guaranteed. Good for independent scripts like analytics.
  • type="module": deferred by default, strict mode, its own scope, supports import, fetched with CORS, and runs only once even if included twice. async works on modules; defer has no extra effect.
  • defer and async are ignored on inline classic scripts (no src). Inline module scripts can use async.
  • nomodule scripts run only in browsers without module support, a legacy fallback pattern.

Interview questions

  • Difference between async and defer?
  • Why does a normal script block HTML parsing?
  • How do module scripts differ from classic scripts?
  • Where should you put script tags today?

data-* attributes

data-* attributes store custom values on elements. JS reads them through element.dataset with camelCase keys.

  • Any attribute starting with data- is valid HTML: data-user-id="42".
  • In JS, el.dataset.userId reads and writes it. Dashes become camelCase; the data- prefix is dropped.
  • Values are always strings. Convert with Number() or JSON.parse when needed.
  • CSS can select and show them: [data-state="open"] and content: attr(data-label).
  • Do not store secrets or large data in them; everything is visible in the page source.
  • They are not for accessibility. Screen readers ignore data-*; use ARIA or real text for that.

Interview questions

  • What are data-* attributes used for?
  • What type is el.dataset.count?

iframes & sandbox

An iframe embeds another page. Restrict it with sandbox and allow, and protect your own pages from being framed.

  • <iframe src> loads a separate document with its own window, JS and DOM. Cross-origin frames cannot read the parent and vice versa (same-origin policy).
  • sandbox with no value applies all restrictions: no scripts, no forms, no popups, unique opaque origin, no top navigation. Add tokens to relax: allow-scripts, allow-forms, allow-popups, allow-same-origin, allow-modals, allow-downloads, allow-top-navigation-by-user-activation.
  • Never combine allow-scripts + allow-same-origin for same-origin content: the frame can then remove its own sandbox attribute.
  • allow sets Permissions Policy for the frame: allow="camera; fullscreen; geolocation 'src'".
  • Parent and frame talk through postMessage. Always check event.origin and send to a specific target origin, not '*'.
  • Accessibility: give each iframe a title describing its content. Performance: loading="lazy" for offscreen embeds.

Interview questions

  • What does the sandbox attribute do?
  • Why is allow-scripts allow-same-origin dangerous?
  • How do you prevent clickjacking?
  • How do a page and its iframe communicate across origins?

HTML5 APIs: storage, canvas vs SVG, workers, geolocation

Know when to use each browser storage, canvas vs SVG, why workers exist, and that powerful APIs need HTTPS and permission.

  • localStorage: per origin, survives restarts, synchronous, strings only, roughly 5 MB. sessionStorage: same API but per tab and cleared when the tab closes.
  • IndexedDB: async, stores structured objects and blobs, large quotas, transactions and indexes. Use it for offline data.
  • Cookies: about 4 KB, sent with every matching request. Use HttpOnly, Secure, SameSite for session tokens; JS cannot read HttpOnly cookies.
  • Canvas is an immediate-mode bitmap you draw on with JS. SVG is vector markup that lives in the DOM, scales cleanly and can be styled, clicked and made accessible.
  • Web Workers run JS on a background thread with no DOM access. They talk via postMessage (data is structured-cloned or transferred). Service Workers are a special worker that proxies network requests for offline and push.
  • Geolocation (navigator.geolocation.getCurrentPosition) needs a secure context (HTTPS) and user permission. Same for camera, mic, clipboard read and notifications.

Interview questions

  • Difference between localStorage, sessionStorage and cookies?
  • When would you choose canvas over SVG?
  • What are Web Workers and what can't they do?
  • Why does geolocation fail on an HTTP site?

SEO basics for developers

Search engines need crawlable URLs, meaningful HTML, unique titles and descriptions, and fast pages.

  • Crawlable: real <a href> links (not click handlers), a sitemap.xml, and a robots.txt that does not block important pages.
  • Indexable: content in the HTML (SSR or static rendering is safest; Google can render JS but later and with limits), and no accidental noindex.
  • On-page: a unique <title> and meta description per page, one clear <h1>, logical headings, descriptive link text, image alt text.
  • rel="canonical" picks the main URL when the same content lives at several URLs (tracking params, sorting).
  • Structured data (JSON-LD with schema.org types like Product, Article, FAQPage) can enable rich results.
  • Core Web Vitals (LCP, INP, CLS) are a ranking signal. INP replaced FID in March 2024.
  • robots.txt blocks crawling, not indexing. To keep a page out of results, use noindex and let it be crawled.

Interview questions

  • What HTML matters most for SEO?
  • How does client-side rendering affect SEO?
  • robots.txt vs noindex?

Accessibility foundations

WCAG: POUR & conformance levels

WCAG is the W3C standard for web accessibility: 4 principles (POUR), testable success criteria, and levels A, AA and AAA.

  • Perceivable: users can sense the content (alt text, captions, contrast, text that resizes).
  • Operable: users can use the UI (keyboard access, enough time, no seizure triggers, clear navigation, target size).
  • Understandable: content and behaviour are predictable (language set, consistent navigation, helpful error messages).
  • Robust: works with current and future assistive tech (valid semantics, correct name/role/value).
  • Levels: A (minimum), AA (the usual target in laws and contracts), AAA (enhanced; not required for whole sites).
  • WCAG 2.2 (October 2023) is current. It added 9 criteria, including Focus Not Obscured (AA), Dragging Movements (AA), Target Size Minimum 24×24 CSS px (AA), Consistent Help (A), Redundant Entry (A) and Accessible Authentication (AA). It removed 4.1.1 Parsing.
  • Laws reference it: ADA (US, enforced through courts), Section 508 (US federal), EN 301 549 and the European Accessibility Act (applies since 28 June 2025).

Interview questions

  • What does POUR stand for?
  • What are WCAG conformance levels and which one do you target?
  • What changed in WCAG 2.2?

ARIA: rules, roles, states & properties

ARIA changes only what assistive tech is told, never behaviour. Use native HTML first and ARIA to fill real gaps.

  • Rule 1: if a native element has the semantics and behaviour you need, use it (<button>, not <div role="button">).
  • Rule 2: do not change native semantics unless you must (no <h2 role="tab">; wrap instead).
  • Rule 3: every interactive ARIA control must be keyboard operable. ARIA adds no keyboard support.
  • Rule 4: never put role="presentation" or aria-hidden="true" on a focusable element.
  • Rule 5: every interactive element needs an accessible name.
  • Roles say what it is (dialog, tab, tablist, menu, switch, alert, landmarks). States change often (aria-expanded, aria-checked, aria-pressed, aria-selected, aria-disabled, aria-current). Properties are mostly stable (aria-label, aria-controls, aria-describedby, aria-haspopup, aria-required).
  • aria-hidden="true" removes an element and its children from the accessibility tree, but it stays visible and clickable.

Interview questions

  • What is ARIA and when should you use it?
  • What is the first rule of ARIA?
  • Difference between ARIA states and properties?
  • aria-hidden="true" vs hidden vs display:none?

aria-label vs aria-labelledby vs aria-describedby

The name says what a control is; the description adds extra help. aria-labelledby > aria-label > native label in priority.

  • Accessible name order (simplified): aria-labelledby → aria-label → native source (<label>, alt, <caption>, <legend>, <title> in SVG) → element text content (for roles like button and link) → title / placeholder as last resort.
  • aria-labelledby points to one or more ids of visible text on the page. It works even if the referenced element is hidden, and you can join several ids.
  • aria-label is an invisible string. Use it when there is no visible text, like an icon-only button.
  • aria-describedby points to extra info (hints, errors, format rules). Screen readers read it after the name and role, often after a pause.
  • Names should be short. Put instructions in the description, not the name.
  • WCAG 2.5.3 Label in Name: the accessible name must contain the visible label text, so voice users can say "click Submit".

Interview questions

  • Difference between aria-label, aria-labelledby and aria-describedby?
  • What is the accessible name and how is it computed?
  • Why might aria-label be the wrong choice even if it works?

Color contrast & use of color

AA needs 4.5:1 for normal text, 3:1 for large text and for UI parts, and color must never be the only signal.

  • 1.4.3 Contrast (Minimum, AA): 4.5:1 for normal text, 3:1 for large text (at least 18pt / 24px, or 14pt / ~18.66px bold).
  • 1.4.6 Contrast (Enhanced, AAA): 7:1 normal, 4.5:1 large.
  • 1.4.11 Non-text Contrast (AA): 3:1 for UI component boundaries, icons that carry meaning, and focus indicators against neighbouring colors.
  • 1.4.1 Use of Color (A): do not show meaning with color alone. Add text, icons or underlines (red error border + an error message; links underlined in body text).
  • Disabled controls and pure decoration are exempt from contrast rules. Logos are exempt too.
  • Respect user settings: prefers-color-scheme, prefers-contrast, forced-colors (Windows High Contrast) and prefers-reduced-motion.

Interview questions

  • What are the WCAG contrast requirements?
  • How is the contrast ratio calculated?
  • What does "don't use color alone" mean in practice?

Keyboard, screen readers & testing

Keyboard navigation, focus, tabindex & skip links

Everything must work with Tab, Shift+Tab, Enter, Space, Esc and arrows, with a visible focus ring and a logical order.

  • Natively focusable: a[href], button, input, select, textarea, summary, elements with contenteditable or tabindex. Use these and you get keyboard support for free.
  • tabindex="0": add to the tab order at its DOM position. tabindex="-1": focusable only by el.focus(), used for headings, error summaries and dialog containers. Positive values jump ahead of everything; avoid them.
  • Focus order follows DOM order. If CSS (flex order, grid placement, absolute positioning) moves things visually, the tab order no longer matches what users see (WCAG 2.4.3).
  • Never remove the outline without a replacement. Use :focus-visible to show rings for keyboard users but not on mouse clicks (2.4.7).
  • Skip link: the first focusable element, "Skip to main content", jumping to <main id="main">. It satisfies 2.4.1 Bypass Blocks. It can be hidden until focused.
  • Composite widgets (tabs, menus, listboxes, grids) use one tab stop plus arrow keys inside. Implement with roving tabindex or aria-activedescendant.
  • No keyboard traps (2.1.2): users must always be able to Tab or Esc out. Modals trap on purpose but must close with Esc.

Interview questions

  • Explain tabindex values.
  • What is a skip link and why is it needed?
  • :focus vs :focus-visible?
  • What is roving tabindex?

Screen readers & live regions

Screen readers read the accessibility tree. Content that changes without focus moving must be announced through a live region.

  • Main screen readers: NVDA (free, Windows), JAWS (Windows), VoiceOver (macOS, iOS), TalkBack (Android), Narrator (Windows).
  • Users navigate by headings, landmarks, links and form fields, not only top to bottom. Good structure is the biggest win.
  • Windows screen readers have browse mode (arrow keys read the page) and focus/forms mode (keys go to the control). Custom widgets with the right roles switch modes correctly.
  • aria-live="polite" waits until the user is idle; "assertive" interrupts. role="status" is polite, role="alert" is assertive. Also role="log", role="timer", role="marquee".
  • The live region must already be in the DOM (it can be empty) before you change its text. Inserting a new region with text often is not announced.
  • aria-atomic="true" reads the whole region instead of only the changed part. aria-busy="true" asks to wait until a batch of updates is done.
  • Hide text visually but keep it for screen readers with a visually-hidden class, not display:none.

Interview questions

  • What is a live region?
  • Difference between aria-live="polite" and "assertive"?
  • Why is my live region not announced?
  • How do you hide something visually but keep it for screen readers?

Accessible modals & dialogs

A modal must move focus in, keep it in, close on Esc, hide the background from assistive tech, and return focus when it closes.

  • Native <dialog> + showModal() gives most of it for free: top layer, ::backdrop, the rest of the page made inert, focus moved inside, and Esc fires cancel and closes it.
  • dialog.show() opens a non-modal dialog (no inertness, no Esc by default). dialog.close(value) closes and sets returnValue.
  • Name the dialog with aria-labelledby pointing at its heading. Add aria-describedby for a short message if helpful.
  • Initial focus: the first sensible control, or autofocus on a specific element. For destructive confirmations, focus the safe option (Cancel).
  • On close, focus must go back to the element that opened it. Browsers do this for <dialog>, but custom modals must store and restore it.
  • Custom modal checklist: role="dialog" + aria-modal="true", focus trap (Tab wraps), Esc closes, background inert, scroll lock, restore focus.

Interview questions

  • How do you build an accessible modal?
  • What does the inert attribute do?
  • Why must focus return to the trigger after closing?
  • Difference between show() and showModal()?

Accessibility testing tools & process

Combine automated checks (axe, Lighthouse) with manual keyboard, screen-reader and zoom testing. Automation alone is not enough.

  • axe-core (Deque) is the engine behind the axe DevTools extension and integrations like jest-axe, @axe-core/playwright and Cypress plugins. Run it in CI.
  • Lighthouse (in Chrome DevTools) gives an accessibility score using a subset of axe rules. A 100 score does not mean the page is accessible.
  • Other tools: WAVE (visual overlay), Accessibility Insights (guided manual checks), eslint-plugin-jsx-a11y for React, Pa11y for CLI, and the DevTools accessibility tree and contrast picker.
  • Automated tools catch things like missing alt, missing labels, low contrast, bad ARIA attributes and duplicate ids. They cannot judge whether alt text is meaningful, focus order is logical or a custom widget works with the keyboard.
  • Manual checks: keyboard only (Tab, Shift+Tab, Enter, Space, Esc, arrows), screen reader (NVDA + Firefox/Chrome, VoiceOver + Safari), zoom to 200% and reflow at 320 CSS px wide (1.4.10), reduced motion, Windows High Contrast.
  • Best: test with real disabled users, and shift left: design reviews, component library with accessibility built in, CI gates.

Interview questions

  • How do you test a page for accessibility?
  • Lighthouse gives 100 for accessibility. Is the site accessible?
  • How would you bring accessibility into a team's process?