FE·13
HTML
HTML as a structure and semantics language: document anatomy, the core elements, semantic meaning and content models, forms end to end, and how scripts and resources load.
Start here: writing HTML that means something
Elements, tags and attributes
HTML is made of elements. Most have a start tag, content and an end tag; the start tag can carry attributes (name–value pairs that configure the element):
<a href="/menu" title="See today's menu">Menu</a>
<!-- ^ tag ^ attribute ^ attribute ^ content ^ end tag -->
- Tag names and attribute names are case-insensitive; write them lowercase.
- Attribute values go in double quotes. Some attributes are boolean: their presence means true (
<input required>,<button disabled>). - A few elements are void: they can't have content, so they have no end tag:
<img>,<br>,<hr>,<input>,<meta>,<link>. - Elements nest, and must close in the reverse order they opened, like brackets:
<p><strong>yes</strong></p>, never<p><strong>no</p></strong>. <!-- comments -->are ignored by the browser.
The skeleton every page shares
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sharma's Tiffin Centre</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- everything visible goes here -->
</body>
</html>
The new line is the viewport <meta>: without it, phones pretend to be a 980-pixel-wide desktop screen and shrink your page to fit, so text becomes unreadably small. Every page you make from now on should have these lines.
Text: headings, paragraphs, lists and emphasis
<h1>Sharma's Tiffin Centre</h1>
<p>Fresh South Indian breakfast since 1998. <strong>Open every day</strong> from 7 am.</p>
<h2>Breakfast</h2>
<ul>
<li>Masala dosa</li>
<li>Idli with sambar</li>
</ul>
<h2>How to order</h2>
<ol>
<li>Choose your dishes.</li>
<li>Pay at the counter.</li>
</ol>
<h1>…<h6>are headings, ranked by importance, not by size: one<h1>for the page's main title,<h2>for its sections,<h3>inside those. Don't skip levels to get smaller text; that's CSS's job.<p>is a paragraph. Line breaks and extra spaces inside your HTML file are collapsed into single spaces, so press Enter as much as you like.<ul>is an unordered (bulleted) list;<ol>an ordered (numbered) one; both contain<li>items.<strong>means "important",<em>means "stressed emphasis" (the way you'd say it). They happen to look bold and italic, but their meaning is what screen readers and search engines use.
Links and images
<a href="https://maps.example.com/sharma-tiffin">Find us on the map</a>
<a href="/menu">Full menu</a>
<a href="#reviews">Jump to reviews</a>
<a href="mailto:hello@sharmatiffin.in">Email us</a>
<img src="dosa.jpg" alt="A golden masala dosa with coconut chutney" width="800" height="533">
hrefcan be an absolute URL, a path on the same site, a#fragmenton the same page, or a scheme likemailto:ortel:(chapter 12's URL rules).- Link text should make sense on its own: "Full menu", not "click here". Screen-reader users often jump from link to link and hear only the text.
- Every
<img>needsalttext: what the image conveys, for people who can't see it (and for when it fails to load). A purely decorative image getsalt=""so it's skipped. widthandheighttell the browser the image's shape before it downloads, so the text below doesn't jump when it arrives. The lab measures the difference.
Semantic HTML: say what things are
You can build a page that looks right using only <div> and <span> with CSS. It will be wrong. Compare two versions of the same content, and what the browser's accessibility tree (what screen readers announce) contains for each, captured from Chromium:
<!-- semantic -->
<header><nav aria-label="Main"><a href="/">Home</a> <a href="/menu">Menu</a></nav></header>
<main><h1>Today's specials</h1><ul><li>Dosa</li><li>Idli</li></ul>
<button type="button">Order</button></main>
<!-- "div soup" -->
<div class="header"><div class="nav"><span class="link" onclick="location='/'">Home</span> …</div></div>
<div class="main"><div class="h1">Today's specials</div><div>Dosa</div><div>Idli</div>
<div class="btn" onclick="…">Order</div></div>
semantic: div soup:
- banner: - text: Home Menu Today's specials Dosa Idli Order
- navigation "Main":
- link "Home"
- link "Menu"
- main:
- heading "Today's specials" [level=1]
- list:
- listitem: Dosa
- listitem: Idli
- button "Order"
The semantic page tells assistive technology there's a navigation area with two links, a main region, a heading, a two-item list and a button. The div version is one undifferentiated string of text. And it isn't only about screen readers. Pressing Tab moves keyboard focus through the semantic page's links and button, and Enter or Space presses the button; on the div version, Tab reaches nothing and the "button" can't be pressed without a mouse (the lab shows both). Search engines, reader modes, browser translation and automated tests all rely on the same meaning.
The everyday rule: use the element whose meaning matches the thing. Navigation goes in <nav>; the page's main content in <main>; a self-contained piece (a blog post, a product card) in <article>; a thematic group with a heading in <section>; something that goes somewhere is a link <a href>; something that does something on this page is a <button>.
Tables for tabular data
<table>
<caption>Breakfast prices</caption>
<thead><tr><th scope="col">Dish</th><th scope="col">Price (₹)</th></tr></thead>
<tbody>
<tr><th scope="row">Masala dosa</th><td>90</td></tr>
<tr><th scope="row">Idli (2)</th><td>50</td></tr>
</tbody>
</table>
Use tables for data with rows and columns (prices, schedules, comparisons), never for page layout (that's CSS grid, chapter 14). <th> cells are headers; scope says whether they head a column or a row, so a screen reader can announce "Idli (2), Price, 50".
Forms: collecting input
A form gathers input and sends it somewhere. The minimum:
<form action="/search" method="get">
<label for="q">Search the menu</label>
<input id="q" name="q" type="search" required>
<label><input type="checkbox" name="veg"> Vegetarian only</label>
<button>Search</button>
</form>
- Each input has a
name: the key it's sent under. Without a name, a field isn't sent at all. - Each input has a
<label>, either linked byfor/idor wrapping the input. Clicking the label focuses the field, and screen readers read it. A placeholder is not a label (it disappears when you type). typechanges the control and the phone keyboard:email,tel,number,date,password,checkbox,radio,file.required,min,max,minlength,patterngive free validation: the browser refuses to submit and shows a message.- A
<button>inside a form submits it.
Typing "masala dosa", ticking the box and pressing Search sends this request (as received by a test server):
GET /search?q=masala+dosa&veg=on
With method="get", the fields become the URL's query string (a space becomes +; a ticked checkbox sends on). That suits searches, which you want to bookmark and share. Forms that change something (place an order, log in) use method="post", which puts the fields in the request body instead; the lab shows both, plus file uploads.
Media, embeds and graphics, briefly
<video src="…" controls>and<audio src="…" controls>play media with built-in controls; add<track>for captions.<iframe src="…">embeds another page (a map, a video player) in a box. It's a separate document, often from another origin.- SVG draws vector graphics in markup (
<svg><circle cx="50" cy="50" r="40"/></svg>); it scales without blurring. The diagrams in this book are SVG. <canvas>is a blank bitmap that JavaScript draws on, pixel by pixel, for charts and games.
How deep to go in HTML
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Name the common elements and attributes; recognise semantic vs presentational markup |
| L2 | Write valid, semantic pages and accessible forms with native validation |
| L3 | Explain implicit roles, content models, default behaviours, form submission encoding and script/resource loading |
| L4 | Diagnose missing form data, broken validation, focus and keyboard bugs, layout shift and slow module graphs |
| L5 | Choose between native elements and custom widgets, design form flows and a loading strategy |
| L6 | Keep large sites semantic, accessible and fast across teams (linting, audits, design-system components) |
Document fundamentals
Document structure
Every HTML page should start from this skeleton:
<!doctype html> <!-- standards mode; without it you get quirks mode -->
<html lang="en"> <!-- language: screen-reader pronunciation, hyphenation, translation -->
<head>
<meta charset="utf-8"> <!-- must be in the first 1024 bytes -->
<meta name="viewport" content="width=device-width, initial-scale=1"> <!-- mobile layout -->
<title>Cart · Shop</title> <!-- tab title, bookmarks, search results, screen readers -->
<link rel="stylesheet" href="/app.css">
<script type="module" src="/app.js"></script> <!-- modules are deferred by default -->
</head>
<body>
<header>…</header>
<main>…</main>
<footer>…</footer>
</body>
</html>
<!doctype html>is the only doctype you need. It switches on standards mode.langdrives pronunciation in screen readers, CSShyphens, spell-checking, and browser translation prompts. Mark changes of language inline:<span lang="te">నమస్కారం</span>.- The viewport meta tag stops mobile browsers from rendering the page at about 980 px wide and zooming out. Don't add
user-scalable=noormaximum-scale=1: blocking zoom fails WCAG (chapter 20).
HTML is parsed by a precisely specified, error-tolerant state machine. Omitted end tags (</p>, </li>, even </body>) are legal in many places, and malformed markup is repaired in standard ways. But "the browser fixed it" means "the browser guessed". Validate with the W3C Nu checker, or with linters in CI.
Metadata
<head> holds information about the document rather than content:
<meta name="description" content="Track your orders and returns."> <!-- search result snippet -->
<link rel="canonical" href="https://shop.example.com/cart"> <!-- deduplicate URLs for SEO -->
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="manifest" href="/manifest.webmanifest"> <!-- PWA, chapter 29 -->
<meta name="theme-color" content="#0d6e69"> <!-- browser UI colour -->
<meta name="color-scheme" content="light dark"> <!-- native controls follow the theme -->
<!-- Social previews (Open Graph / Twitter cards) -->
<meta property="og:title" content="Your cart">
<meta property="og:image" content="https://shop.example.com/og/cart.png">
<!-- Security policy can be a meta tag, though headers are preferred (chapter 28) -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
<!-- Structured data for search engines -->
<script type="application/ld+json">{"@context":"https://schema.org","@type":"Product","name":"Socks"}</script>
Headings, sections and landmarks
Headings (<h1>–<h6>) form the document's outline. Screen-reader users navigate by them constantly: listing headings is often their first action on a new page. The rules:
- Use one
<h1>per page for the page's main topic. - Don't skip levels to get a smaller font (h2 → h4). Choose the level by structure and style it with CSS.
- Never use bold text or a
<div class="title">where a heading belongs.
The old "document outline algorithm" (where <section> would demote headings automatically) was never implemented by any browser and has been removed from the spec. Heading levels are what you write.
Sectioning and landmark elements give regions a role that assistive technology exposes as landmarks for quick navigation:
| Element | Landmark role | Meaning |
|---|---|---|
<header> (top-level) |
banner |
Site header: logo, global navigation |
<nav> |
navigation |
A major group of navigation links |
<main> |
main |
The primary content. One per page, and the target of "skip to content" links |
<aside> |
complementary |
Related but separate content (sidebar) |
<footer> (top-level) |
contentinfo |
Site footer |
<section> with an accessible name |
region |
A thematic group, usually with a heading |
<form> with an accessible name |
form |
|
<search> |
search |
A search area (a newer element) |
<article> |
article |
Self-contained content: a post, a comment, a product card |
Paragraphs, text-level semantics and lists
Text content has semantic elements too, and each one changes meaning, not just appearance:
| Element | Meaning | Not for |
|---|---|---|
<p> |
A paragraph | Spacing (use CSS) |
<strong> |
Importance, seriousness, urgency | Merely bold styling (use CSS or <b> for stylistic offset) |
<em> |
Stress emphasis that changes meaning ("I didn't say that") | Italics for titles (<cite>) or foreign words (<i lang>) |
<code>, <kbd>, <samp>, <var> |
Code, keyboard input, program output, variables | |
<abbr title> |
Abbreviation | |
<time datetime="2026-10-24"> |
Machine-readable date or time | |
<mark> |
Highlighted relevance (search hits) | |
<blockquote>, <q>, <cite> |
Quotations and the title of a work | |
<br> |
A line break that is part of the content (addresses, poems) | Spacing |
<pre> |
Preformatted text, with whitespace preserved | |
<sup>, <sub> |
Superscript and subscript with meaning (x², H₂O) | |
<details> + <summary> |
A native disclosure widget (accordion) that is keyboard-accessible for free | |
<dialog> |
A modal or non-modal dialog (chapter 20) |
Lists: <ul> (unordered), <ol> (ordered, with start and reversed), and <dl> (description list: <dt> term and <dd> details, good for key–value metadata). Screen readers announce "list, 5 items", which helps users orient themselves. Navigation menus are conventionally a <ul> of links inside <nav>.
Links and buttons
The most important semantic distinction in interactive HTML:
- A link (
<a href>) navigates: it goes to a URL. It supports open-in-new-tab, copy link, middle-click, bookmarking and history. It's activated with Enter. - A button (
<button>) performs an action on the current page: submit, open a menu, toggle, delete. It's activated with Enter and Space.
<a href="/orders/42">View order 42</a> <!-- navigation -->
<button type="button" onclick="openFilters()">Filters</button> <!-- action -->
<!-- Anti-patterns -->
<a href="#" onclick="save()">Save</a> <!-- a fake link: wrong semantics, adds "#" to history -->
<div onclick="save()">Save</div> <!-- not focusable, no role, no keyboard support -->
<a>Click here</a> <!-- an <a> without href isn't focusable -->
Details that matter:
- Default button type:
<button>inside a<form>defaults totype="submit". Writetype="button"for buttons that shouldn't submit, or you'll get accidental form submissions. - Link text must make sense out of context. Screen-reader users list all links on a page, and "click here" and "read more" ×12 are useless. Write "Read the refund policy".
target="_blank": modern browsers implyrel="noopener", which stops the new page from controlling yours throughwindow.opener(a phishing technique called reverse tabnabbing). Tell users a link opens a new tab, visually and in its text.downloadmakes a link download its target, andrel="nofollow ugc sponsored"gives search engines hints.
Images
<img src="/img/socks-800.jpg"
srcset="/img/socks-400.jpg 400w, /img/socks-800.jpg 800w, /img/socks-1600.jpg 1600w"
sizes="(min-width: 60rem) 50vw, 100vw"
width="800" height="600"
alt="Red wool socks with a white heel"
loading="lazy" decoding="async">
altis required. It's the text alternative, read by screen readers, shown when the image fails to load, and used by search engines. Describe the image's purpose in context. For purely decorative images, usealt=""(empty), so screen readers skip it. Omittingaltis worse: many screen readers then read the file name.widthandheightlet the browser reserve space before the image loads, which prevents layout shift (CLS, chapter 27). CSS can still make the image responsive (max-width: 100%; height: auto), and the browser derives the aspect ratio from the attributes.- Responsive images:
srcsetwithwdescriptors plussizeslets the browser pick a file by display size and pixel density.<picture>with<source>handles art direction (different crops for different layouts) and format fallback:
<picture>
<source type="image/avif" srcset="hero.avif">
<source type="image/webp" srcset="hero.webp">
<img src="hero.jpg" alt="…" width="1200" height="600" fetchpriority="high"> <!-- the LCP image: load eagerly -->
</picture>
loading="lazy"defers off-screen images. Never lazy-load the LCP image (usually the hero image), because it delays the most important paint.
Tables
Tables are for tabular data: rows and columns with relationships between them. Don't use them for page layout (that's a 1990s practice that confuses screen readers). Accessible table markup:
<table>
<caption>Orders in October 2026</caption> <!-- the table's accessible name -->
<thead>
<tr><th scope="col">Order</th><th scope="col">Date</th><th scope="col">Total</th></tr>
</thead>
<tbody>
<tr><th scope="row">#1042</th><td><time datetime="2026-10-03">3 Oct</time></td><td>₹2,499</td></tr>
<tr><th scope="row">#1043</th><td><time datetime="2026-10-11">11 Oct</time></td><td>₹899</td></tr>
</tbody>
</table>
<th> with scope lets screen readers announce "Total, ₹899" as the user moves between cells. For complex tables, use headers/id associations. Wide tables should scroll inside a container (overflow-x: auto) at small widths rather than break the page. If you build an interactive data grid (sortable, editable, keyboard-navigable), that's an ARIA grid pattern (chapter 20). Prefer a well-tested library.
Media, embeds, iframes, SVG and canvas
<video>and<audio>: native players withcontrols,<source>fallbacks, and<track kind="captions">in WebVTT format. Captions are a WCAG requirement for prerecorded video. Browsers allow autoplay only when the media ismuted. Addplaysinlinefor iOS.<iframe>: embeds another document in its own browsing context. Harden embeds withsandbox(no scripts, forms or top navigation unless re-allowed),allow(Permissions Policy:allow="fullscreen; payment"),loading="lazy",referrerpolicy, and atitle(an iframe's accessible name). Your own pages can refuse to be framed with CSPframe-ancestors(chapter 28).- SVG: vector graphics as markup, with
viewBox, shapes, paths, text and gradients. It's resolution-independent, styleable with CSS, scriptable, and accessible (<title>,role="img",aria-label). Use it for icons, logos, diagrams and charts. Inline SVG can usecurrentColorto inherit text colour. Sanitise untrusted SVG, because it can contain scripts. <canvas>: an immediate-mode bitmap you draw with JavaScript (the 2D context, WebGL, WebGPU). Use it for games, charts with thousands of points, image editing and visualisations. A canvas is a black box to assistive technology, so provide text alternatives or a parallel accessible DOM.OffscreenCanvaslets workers render (chapter 29).
| Need | Use |
|---|---|
| Icons, logos, simple diagrams, crisp at any zoom | SVG |
| A chart with < ~5,000 elements, interactive, accessible | SVG (or HTML) |
| 10⁴–10⁶ points, particles, games, pixel manipulation | Canvas / WebGL |
| 3D, GPU compute | WebGL / WebGPU |
Semantic HTML
Implicit semantics
Every HTML element has an implicit ARIA role and built-in behaviour, defined in the HTML-AAM and ARIA in HTML specs:
| Element | Implicit role | Free behaviour |
|---|---|---|
<button> |
button | Focusable, Enter/Space activation, disabled, form submission |
<a href> |
link | Focusable, Enter activation, context menu, history |
<input type="checkbox"> |
checkbox | Checked state, Space toggles, label association |
<nav> |
navigation | Landmark |
<h2> |
heading (level 2) | Outline navigation |
<ul> / <li> |
list / listitem | Item count announced |
<select> |
combobox / listbox | Full keyboard support, native mobile pickers |
<dialog> with showModal() |
dialog | Focus trapping, Esc to close, inert background, top layer |
<details> |
group, with a summary that acts as a disclosure button | Expand/collapse via keyboard |
<table> with <th> |
table / columnheader | Cell-to-header announcements |
Choosing the right element gives you keyboard support, focus behaviour, screen-reader semantics, form participation, and browser features (autofill, reader mode, translation, search indexing) at zero cost. A <div> with ARIA can imitate some of it, but you must re-implement the behaviour yourself and keep it correct.
Content models
Each element's spec defines its content model: what it may contain. Content is grouped into categories such as flow, phrasing (inline-level text), interactive, heading, sectioning and embedded content. Violations get "fixed" by the parser in ways that break your layout or script assumptions:
<p>accepts only phrasing content. A<div>,<ul>or another<p>inside it closes the paragraph early, so<p><div>x</div></p>becomes<p></p><div>x</div><p></p>.- Interactive content can't nest: no
<a>inside<a>, and no<button>inside<a>or<button>. "Clickable card with a nested button" designs need a different structure. Use a link that covers the card through a positioned pseudo-element, with the inner buttons above it. <a>is transparent: it may wrap block content such as a whole card (allowed since HTML5) as long as there's no interactive content inside.<table>has strict children. Stray<div>s get foster-parented out of the table.<ul>/<ol>may only contain<li>(plus<script>/<template>).
Framework templates hide this, but React and Angular still produce DOM that the HTML parser would reject, and server-rendered HTML with invalid nesting is a classic cause of hydration mismatches (chapter 22): the server's HTML gets re-parsed into a different tree than the client expected.
Default browser behaviour
Native elements come with behaviour you'd otherwise have to rebuild:
- Forms submit on Enter in a text field, validate with constraint validation, and work without JavaScript.
- Links support every navigation affordance: new tab, prefetch, history,
:visitedstyling. - Focus order follows DOM order. Interactive elements are in the tab sequence automatically.
- Native controls adapt to the platform: date pickers, mobile keyboards chosen by
typeandinputmode, password managers, autofill, OS-level accessibility, and high-contrast modes. - Find-in-page, reader mode, translation and text selection all understand real text in the DOM, which canvas-rendered or image-based text breaks.
hidden="until-found"keeps collapsed content searchable by find-in-page, which auto-expands it.
Removing default behaviour usually costs you. outline: none without a replacement focus style, user-select: none on content, or a form that doesn't submit on Enter each degrade the experience.
Accessibility implications
Semantic HTML is the foundation of accessibility (chapter 20). The first rule of ARIA is: if a native HTML element or attribute with the semantics and behaviour you need already exists, use it instead of repurposing an element and adding ARIA. A practical checklist for every page:
- Use landmarks: one
<main>, a<nav>for the main navigation,<header>and<footer>. - Use a logical heading hierarchy that starts at one
<h1>. - Make every interactive thing a real
<button>,<a href>or form control. - Give every image an appropriate
alt(empty for decoration). - Associate a visible
<label>with every form control (next section). - Set
langon<html>. - Give data tables captions and header cells.
- Make link and button text meaningful out of context.
- Make sure the DOM order matches the visual and reading order, because CSS reordering (
order, grid placement) doesn't change the focus order.
Forms
Form anatomy and submission
A <form> gathers user input and submits it as an HTTP request:
<form action="/signup" method="post">
<label for="email">Email</label>
<input id="email" name="email" type="email" autocomplete="email" required>
<label for="pw">Password</label>
<input id="pw" name="password" type="password" autocomplete="new-password"
minlength="12" required aria-describedby="pw-hint">
<p id="pw-hint">At least 12 characters.</p>
<button type="submit">Create account</button>
</form>
- The
nameattribute is the key in the submitted data. A control without anameis not submitted. method="get"puts fields in the URL query string (search forms: bookmarkable and shareable).method="post"puts them in the request body (anything that changes state, or that contains passwords).- Encoding (
enctype): the default isapplication/x-www-form-urlencoded(email=a%40b.com&password=…),multipart/form-datais required for file uploads, andtext/plainis for debugging only. - Submission happens on a submit button click, or Enter in a single-line field. In JavaScript, listen for the form's
submitevent, not a button'sclick, so keyboard submission and validation are handled too.
Input types
The type attribute chooses the control, its validation, and the mobile keyboard:
| Type | Gives you |
|---|---|
text, search |
Plain text; search may show a clear button |
email |
@ keyboard on mobile; format validation |
tel |
Phone keypad (no validation, because formats vary) |
url |
URL keyboard; URL validation |
number |
Spinner; numeric validation. Avoid it for codes and IDs (card numbers, OTPs, PINs): use type="text" inputmode="numeric" pattern="[0-9]*" instead |
password |
Masked; password-manager integration |
date, time, datetime-local, month, week |
Native pickers (styling is limited) |
checkbox, radio |
Grouped by name; radios are mutually exclusive |
range, color, file, hidden |
inputmode (numeric, decimal, tel, email, url, search) changes the virtual keyboard without changing validation. enterkeyhint (search, send, next, done) labels the Enter key on mobile.
Labels, fieldsets and legends
Every control needs a label. It's the control's accessible name, and clicking a label focuses or toggles its control, which makes checkboxes and radios much easier to hit.
<!-- explicit association -->
<label for="qty">Quantity</label> <input id="qty" name="qty" type="number" min="1" value="1">
<!-- implicit association (wrapping) -->
<label><input type="checkbox" name="terms" required> I accept the terms</label>
<!-- grouping related controls: the legend names the group -->
<fieldset>
<legend>Delivery speed</legend>
<label><input type="radio" name="speed" value="std" checked> Standard (3–5 days)</label>
<label><input type="radio" name="speed" value="exp"> Express (next day)</label>
</fieldset>
Placeholder text isn't a label. It disappears while typing, usually has poor contrast, and isn't reliably announced. Use visible labels, and use aria-describedby to connect hint and error text to the control.
Select and textarea
<label for="country">Country</label>
<select id="country" name="country" autocomplete="country">
<option value="">Choose…</option>
<optgroup label="Asia">
<option value="IN" selected>India</option>
<option value="SG">Singapore</option>
</optgroup>
</select>
<label for="notes">Delivery notes</label>
<textarea id="notes" name="notes" rows="4" maxlength="500"></textarea>
Native <select> is fully accessible and uses platform pickers on mobile. Historically it couldn't be styled much, which led to many inaccessible custom dropdowns. Customisable select (appearance: base-select with ::picker(select)) is arriving in Chromium and lets you style the native element instead of rebuilding it. For searchable lists, use <input list> with <datalist> for simple suggestions, or an accessible combobox (chapter 20). field-sizing: content lets a <textarea> grow with its content, without JavaScript, where supported.
Validation
HTML has built-in constraint validation:
| Attribute | Constraint |
|---|---|
required |
Must not be empty |
type="email" / "url" |
Format |
min, max, step |
Numeric and date ranges |
minlength, maxlength |
Length (maxlength also prevents typing beyond it) |
pattern |
Regex for the whole value (anchored automatically) |
Each control exposes validity (valueMissing, typeMismatch, patternMismatch, tooShort, rangeOverflow…), checkValidity(), reportValidity() and setCustomValidity(msg). Submitting a form with invalid controls is blocked, and the browser shows a message near the first invalid field. Add novalidate to the form to show your own UI instead, while still using the API:
const form = document.querySelector("form");
form.addEventListener("submit", (e) => {
const pw = form.elements.password, confirm = form.elements.confirm;
confirm.setCustomValidity(pw.value === confirm.value ? "" : "Passwords don't match");
if (!form.checkValidity()) {
e.preventDefault();
showErrors(form); // render messages next to fields, linked with aria-describedby
form.querySelector(":invalid")?.focus();
}
});
CSS can style the states with :invalid, :valid and :required. Prefer :user-invalid, which matches only after the user has interacted with the field, so a pristine form doesn't load covered in red.
Good validation UX: validate on blur or submit, not on every keystroke while someone is still typing. Put error text next to the field, saying what's wrong and how to fix it. Don't rely on colour alone. Move focus to the first error, or to an error summary, on submit. Keep the user's input.
Autocomplete
The autocomplete attribute tells browsers and password managers exactly what a field is, so autofill works:
<input name="name" autocomplete="name">
<input name="email" autocomplete="email">
<input name="phone" autocomplete="tel">
<input name="address" autocomplete="street-address">
<input name="postcode" autocomplete="postal-code">
<input name="cc" autocomplete="cc-number" inputmode="numeric">
<input name="username" autocomplete="username">
<input name="password" autocomplete="current-password"> <!-- login -->
<input name="newpass" autocomplete="new-password"> <!-- signup / reset: triggers password generation -->
<input name="otp" autocomplete="one-time-code" inputmode="numeric"> <!-- SMS code autofill -->
<input name="passkey" autocomplete="username webauthn"> <!-- passkey autofill (conditional UI) -->
Correct autocomplete values are also a WCAG requirement (1.3.5 Identify Input Purpose). autocomplete="off" is widely ignored for login fields, and blocking password managers makes accounts less secure.
FormData and submitting with JavaScript
FormData collects a form's current values exactly as native submission would, and fetch sends it:
form.addEventListener("submit", async (e) => {
e.preventDefault();
const data = new FormData(form); // includes files; respects disabled/unnamed rules
data.get("email"); // "a@b.com"
Object.fromEntries(data); // { email: "…", password: "…" } (loses repeated keys)
const res = await fetch(form.action, {
method: "POST",
body: data, // the browser sets multipart/form-data + boundary itself
});
// or JSON:
// await fetch("/api/signup", { method: "POST", headers: { "Content-Type": "application/json" },
// body: JSON.stringify(Object.fromEntries(data)) });
});
Don't set Content-Type yourself when sending FormData: the browser must add the multipart boundary. React 19 actions and Next.js server actions (chapters 22 and 24) build on the native form model: <form action={serverFn}> receives a FormData, which brings back progressive enhancement, since the form can work before JavaScript loads.
Multipart and file inputs
multipart/form-data encodes each field as a separate part separated by a random boundary, so binary file content can sit next to text fields:
POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=----x7Fq
------x7Fq
Content-Disposition: form-data; name="title"
Holiday photos
------x7Fq
Content-Disposition: form-data; name="photos"; filename="beach.jpg"
Content-Type: image/jpeg
<binary bytes…>
------x7Fq--
<label for="photos">Photos</label>
<input id="photos" name="photos" type="file" accept="image/*" multiple capture="environment">
const input = document.querySelector("#photos");
input.addEventListener("change", () => {
for (const file of input.files) { // File objects (a kind of Blob): name, size, type, lastModified
if (file.size > 10 * 1024 * 1024) alert(`${file.name} is over 10 MB`);
const preview = URL.createObjectURL(file); // instant local preview; revoke it later
}
});
On the server, every stack parses multipart: Spring's MultipartFile, Go's r.ParseMultipartForm / FormFile, and Rust axum's Multipart extractor. Security rules for uploads: enforce size limits on the server (and in the reverse proxy), never trust the filename or Content-Type (sniff the content and generate your own name), store files outside the web root or in object storage, scan them if needed, and serve user uploads from a separate domain or with Content-Disposition: attachment so uploaded HTML or SVG can't run scripts on your origin. For large files, upload directly to object storage with presigned URLs (S3 or GCS), in resumable chunks (tus, S3 multipart upload), instead of streaming through your app servers.
Loading scripts and resources
Classic scripts: async and defer
How a <script> loads changes parsing and execution order:
| Blocks parser | Execution order | Runs when | |
|---|---|---|---|
<script src> |
Yes | Document order | Immediately after download |
<script async src> |
No | Unordered | As soon as downloaded |
<script defer src> |
No | Document order | After parsing, before DOMContentLoaded |
<script type="module"> |
No | Document order (deferred) | After parsing |
<script type="module" async> |
No | Unordered | As soon as its module graph is ready |
Rules of thumb: use type="module" (or defer) for application code. Use async for independent third-party scripts (analytics), and even those are better loaded late or in a worker (Partytown). Avoid parser-blocking scripts in <head>. document.write from an async script is ignored, and Chrome blocks it on slow connections.
ES modules in the browser
ES modules give the browser real imports:
<script type="importmap">
{ "imports": { "lit": "https://cdn.jsdelivr.net/npm/lit@3.2.1/+esm", "app/": "/js/app/" } }
</script>
<script type="module">
import { LitElement, html } from "lit"; // bare specifier resolved by the import map
import { initCart } from "app/cart.js";
initCart();
</script>
Module scripts are always deferred and run in strict mode. They have their own top-level scope (no implicit globals), support top-level await, are fetched with CORS (so cross-origin modules need Access-Control-Allow-Origin), and execute once however many times they're imported. Import maps map bare specifiers ("lit") to URLs. With import maps and HTTP/2, small apps can ship unbundled ESM. Large apps still bundle (chapter 30), because deep import graphs mean many round trips, called waterfalls.
<script nomodule> was the old fallback for browsers without module support. It's no longer needed for evergreen targets.
preload, prefetch, preconnect and modulepreload
Resource hints tell the browser about resources earlier than it would discover them:
| Hint | Meaning | Use for |
|---|---|---|
<link rel="preconnect" href="https://cdn.example"> |
Do DNS + TCP + TLS now | Critical third-party origins (fonts, CDN, API). Limit to 2–3 |
<link rel="dns-prefetch" href="…"> |
DNS lookup only | A cheap fallback for less critical origins |
<link rel="preload" href="/font.woff2" as="font" type="font/woff2" crossorigin> |
Fetch now, at high priority, for this page | Late-discovered critical resources: fonts referenced from CSS, the LCP image used as a CSS background, critical scripts |
<link rel="modulepreload" href="/js/app.js"> |
Preload and parse a module and its dependencies | Avoiding module-graph waterfalls |
<link rel="prefetch" href="/next-page.js"> |
Fetch at low priority for a likely future navigation | The next step in a flow |
Speculation Rules (<script type="speculationrules">) |
Prerender or prefetch whole pages the user is likely to visit | Near-instant multi-page navigations (Chromium) |
fetchpriority="high" / "low" |
Adjust the priority of an <img>, <script>, <link> or fetch() |
Boost the LCP image; deprioritise below-the-fold content |
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preload" href="/fonts/Inter-var.woff2" as="font" type="font/woff2" crossorigin>
<link rel="modulepreload" href="/js/app.js">
<script type="speculationrules">
{ "prerender": [{ "where": { "href_matches": "/products/*" }, "eagerness": "moderate" }] }
</script>
Preloading has costs. Each preload competes for bandwidth, and preloading something the page doesn't use within a few seconds wastes it (Chrome warns in the console). Fonts must have crossorigin even on the same origin, or they're fetched twice. Measure with the DevTools Network panel's priority column and with WebPageTest waterfalls (chapter 27).
Lab: HTML, measured
Every result below came from Chromium 153 (headless, driven by Playwright) against small Node servers on localhost. Retype the pages, open DevTools, and you'll see the same things.
Experiment 1: what assistive technology and the keyboard get
The two pages from the Start here section, semantic and "div soup", were loaded and probed in two ways: Playwright's ariaSnapshot() (a text dump of the accessibility tree, the same tree screen readers query through the operating system), and the keyboard: press Tab four times recording the focused element, then focus the Order control and press Enter and Space, counting how many times its click handler ran.
for (let i = 0; i < 4; i++) { await page.keyboard.press("Tab"); stops.push(describe(document.activeElement)); }
await page.focus("button"); await page.keyboard.press("Enter"); await page.keyboard.press("Space");
semantic Tab stops: a "Home" → a "Menu" → button "Order" → (body) | Enter+Space activations: 2
div soup Tab stops: (body) → (body) → (body) → (body) | Enter+Space activations: 0
The accessibility trees are the ones shown in Start here: landmarks, a navigation with two links, a heading, a list and a button, against a single line of text. The keyboard result is the starker one: on the div page a keyboard user (or a switch-device user, or anyone with a broken trackpad) can't reach a single control. Fixing the divs properly means adding tabindex="0", role="button", an accessible name, and a keydown handler for Enter and Space (buttons fire on Space key-up, links on Enter only), then focus styles. Or using <button>, which has all of it built in. That's the general lesson of semantic HTML: native elements bring behaviour, not just meaning.
Experiment 2: the browser's built-in validation
A booking form with constraints, loaded with deliberately bad values:
<form method="post" action="/submit">
<label>Name <input name="name" required minlength="2"></label>
<label>Email <input name="email" type="email" required value="asha@"></label>
<label>Guests <input name="guests" type="number" min="1" max="10" value="12"></label>
<label>PIN code <input name="pin" pattern="[0-9]{6}" value="5000"></label>
<button>Book</button>
</form>
Reading each field's constraint validation API (validity and validationMessage) before submitting:
name valid=false Please fill out this field.
email valid=false Please enter a part following '@'. 'asha@' is incomplete.
guests valid=false Value must be less than or equal to 10.
pin valid=false Please match the requested format.
Clicking Book sends nothing while any field is invalid; the browser focuses the first invalid field and shows its message. Each failure also sets a specific flag on input.validity (valueMissing, typeMismatch, rangeOverflow, patternMismatch, tooShort), which lets you write your own messages with setCustomValidity() and style fields with the :user-invalid pseudo-class (which, unlike :invalid, waits until the user has interacted). Note that pattern is anchored automatically: [0-9]{6} means "exactly six digits".
Client-side validation is a convenience for the user, never a security check: anyone can send any request with curl. The server must validate everything again (chapter 28 and Volume 3).
Experiment 3: what a form actually sends
With valid values, the same form was submitted three ways, and the Node server printed each request exactly as it arrived:
POST /submit
Content-Type: application/x-www-form-urlencoded
name=Asha&email=asha%40example.in&guests=4&pin=500039
const fd = new FormData();
fd.append("name", "Asha K"); fd.append("note", "veg & spicy");
fd.append("photo", new Blob(["(binary image bytes)"], { type: "image/png" }), "dosa.png");
await fetch("/submit-multipart", { method: "POST", body: fd });
POST /submit-multipart
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryLEJhjgVffHhxJPLQ
------WebKitFormBoundaryLEJhjgVffHhxJPLQ
Content-Disposition: form-data; name="name"
Asha K
------WebKitFormBoundaryLEJhjgVffHhxJPLQ
Content-Disposition: form-data; name="note"
veg & spicy
------WebKitFormBoundaryLEJhjgVffHhxJPLQ
Content-Disposition: form-data; name="photo"; filename="dosa.png"
Content-Type: image/png
(binary image bytes)
------WebKitFormBoundaryLEJhjgVffHhxJPLQ--
GET /search?q=masala+dosa&veg=on
- URL-encoded (the default for
method="post"): one line ofname=valuepairs joined by&, with special characters escaped (@became%40). Compact, but it can't carry files. - Multipart (
enctype="multipart/form-data", or anyfetchwith aFormDatabody): each field is a separate part between boundary lines, with its own headers, so binary files travel unmodified. Notice thatfetchset theContent-Typeand boundary itself: if you set that header by hand, you'll get the boundary wrong and the server can't parse the body. - GET: the fields go in the URL, so they're visible, bookmarkable, logged by servers and proxies, and limited in length. Never send passwords or personal data this way.
Experiment 4: images, layout shift and lazy loading
A page with a heading, a paragraph and ten 800 × 400 images (each delayed 300 ms by the server), in a 800 × 600 window. A PerformanceObserver added up Cumulative Layout Shift (CLS): how much visible content jumped while the page loaded (chapter 27; 0.1 or less is "good", above 0.25 "poor").
no width/height, eager images requested at load: 10 of 10 | layout shift score (CLS): 0.301
width/height, eager images requested at load: 10 of 10 | layout shift score (CLS): 0.000
width/height, lazy images requested at load: 8 of 10 | layout shift score (CLS): 0.000
Without width and height, each image starts at zero height and pushes the text down when it arrives: a "poor" score from one omission. With them, the browser computes the aspect ratio up front (it maps the attributes to aspect-ratio in its default styles, so height: auto in CSS still works for responsive images) and reserves the space.
loading="lazy" deferred only 2 of the 10 images, though only one fits in the window. Chromium starts loading lazy images well before they scroll into view (a distance of over a thousand pixels, larger on slow connections) so they're ready when you get there. Lazy loading pays off on long pages, and must not be used for the main image at the top (the likely Largest Contentful Paint element), which should load as early as possible, ideally with fetchpriority="high".
Experiment 5: module waterfalls and modulepreload
An entry module a.js imports b.js, which imports c.js; the server delays each file 200 ms. The browser can't know about b.js until it has downloaded and parsed a.js, so the requests form a chain. Adding <link rel="modulepreload"> for the deeper modules tells it in advance:
<link rel="modulepreload" href="/b.js">
<link rel="modulepreload" href="/c.js">
<script type="module" src="/a.js"></script>
without modulepreload module graph a→b→c (200 ms per file) finished at 644 ms
with modulepreload module graph a→b→c (200 ms per file) finished at 218 ms
Three round trips became one. The server's request log showed the difference directly: without the hints, /b.js was requested 213 ms after /a.js and /c.js 206 ms after that; with them, all three within 2 ms of each other. This is why bundlers (chapter 30) either combine modules or emit modulepreload links for the graph, and why deep import chains hurt on high-latency mobile networks. modulepreload also parses and compiles the module ahead of time, which a generic rel="preload" doesn't.
Try it yourself
- Make the div-soup page keyboard-accessible without changing any element to a button or link. Count the attributes and code you needed. Then compare with the semantic version.
- Add
novalidateto the booking form and submit it. What does the server receive? Now write a server-side check for each constraint. - Upload a real photo with a
<input type="file" name="photo" accept="image/*">form, and print the raw request on a Node server. Find the boundary, the part headers and where the binary data starts. - In experiment 4, give only the first image
fetchpriority="high"and measure when it finishes compared with the others (use the Network panel's waterfall).
Revision sheet: HTML
Key ideas
- A document is
<!doctype html>,<html lang>, a<head>(charset, viewport, title, links, scripts) and a<body>. - Choose elements for meaning: landmarks (
header,nav,main,aside,footer), sectioning (article,section), headings in structural order, lists, tables for data,<a href>to go somewhere,<button>to do something. - Implicit semantics: native elements map to accessibility roles automatically (
nav→ navigation,button→ button,ul→ list); ARIA only fills gaps, and "no ARIA is better than bad ARIA". - Content models define what may nest where (no interactive content inside
<a>or<button>, no block elements inside<p>); the parser silently restructures violations. - Default behaviour comes free: focusability, keyboard activation, form submission, link navigation,
<details>disclosure,<dialog>withshowModal()(focus trapping and the top layer). - Forms: every control has a
nameand a<label>; group related controls with<fieldset>/<legend>; use the righttypeandautocompletetokens; constraint validation (required,pattern,min,max,minlength) plussetCustomValidity;:user-invalidfor styling; server-side validation regardless. - Submission: GET puts fields in the query string; POST uses
application/x-www-form-urlencodedby default ormultipart/form-datafor files;FormDatabuilds either from a form or by hand. - Images:
alt,width/heightfor aspect ratio,srcset/sizesand<picture>for responsive and format choices,loading="lazy"below the fold,fetchpriority="high"for the hero. - Loading: classic scripts block parsing;
deferand modules run after parsing in order;asyncon arrival;preloadfor late-discovered critical resources,modulepreloadfor module graphs,preconnectfor early connections to other origins,prefetchfor likely next navigations.
Numbers to remember
- Heading levels: 6. Landmarks a page should have: one
main, usually aheader,navandfooter. - CLS thresholds: good at most 0.1, poor above 0.25.
<meta name="viewport">absent: mobile browsers assume a layout width of about 980 px.
Pitfalls
- Placeholders as labels; inputs without
name; inputs withouttypeon phones (wrong keyboard). - Clickable
divs andspans; links withhref="#"used as buttons; buttons inside forms withouttype="button"that submit unexpectedly. - Skipping heading levels for visual size; multiple
<h1>s used as styling. - Missing
alt, oraltthat repeats nearby text or says "image of". - Setting
Content-Typemanually on aFormDatafetch (breaks the boundary). - Lazy-loading the hero image.
- Treating client-side validation as security.
Glossary
- Void element: an element with no content or end tag (
img,input,br,meta,link). - Landmark: a region role (banner, navigation, main, contentinfo) that assistive tech can jump between.
- Accessible name: the text a control is announced by (from its content, label,
alt,aria-labeloraria-labelledby). - Constraint validation API:
validity,validationMessage,checkValidity(),reportValidity(),setCustomValidity(). - Multipart boundary: the unique separator line between parts of a multipart body.
- Top layer: where modal dialogs and popovers render, above all other content regardless of z-index.