Web Development Cheat Sheet

HTML Cheat Sheet: Tags, Attributes & Examples

Quickly find essential HTML elements, attributes, forms, tables, semantic structures, accessibility guidance, and copyable code examples based on the current HTML Living Standard.

20 structured sections Copyable examples Interactive HTML preview Accessibility guidance

Essential HTML at a glance

HTML Quick Reference

Start with these frequently used elements for page structure, text, links, images, lists, forms, and tabular data.

Common HTML elements with purposes and examples
Element Purpose Example Copy
<h1>–<h6> Define headings at six levels. <h1>Page title</h1>
<p> Represents a paragraph. <p>A useful paragraph.</p>
<a> Creates a hyperlink. <a href="/about/">About us</a>
<img> Embeds an image with a text alternative. <img src="team.jpg" alt="Our support team">
<ul> Contains an unordered list of items. <ul><li>First item</li></ul>
<ol> Contains an ordered list of items. <ol><li>First step</li></ol>
<main> Identifies the document’s dominant content. <main>...</main>
<section> Represents a thematic section, typically with a heading. <section><h2>Features</h2></section>
<article> Represents self-contained, independently reusable content. <article><h2>News title</h2></article>
<button> Creates an interactive button. <button type="button">Open menu</button>
<form> Groups controls for submitting user-provided data. <form action="/subscribe/" method="post">...</form>
<input> Creates a form control whose behavior depends on its type. <input type="email" name="email" autocomplete="email">
<table> Represents data with relationships across rows and columns. <table><tr><th>Name</th></tr></table>
<div> Provides a generic block container when no semantic element fits. <div class="card">...</div>
<span> Provides a generic inline container for phrasing content. <span class="price">$29</span>

Paired element

Most elements have a start tag, content, and an end tag.

<strong>Important text</strong>

Void element

Void elements do not contain children and must not use an end tag.

<hr>

Build a valid page foundation

Basic Document Structure

Every standalone HTML document needs a document type, root element, metadata section, and body containing the page’s visible content.

Components of a basic HTML document
Markup Purpose Recommended example Copy
<!doctype html> Activates standards mode for an HTML document. <!doctype html>
<html> Creates the document root and declares the primary content language. <html lang="en">
<head> Contains document metadata and links to supporting resources. <head>...</head>
<meta charset> Declares the character encoding used by the document. <meta charset="utf-8">
<meta name="viewport"> Configures the initial viewport for responsive layouts. <meta name="viewport" content="width=device-width, initial-scale=1">
<title> Provides the document title used by browsers, bookmarks, and other interfaces. <title>Accessible HTML Guide</title>
<body> Contains the document’s rendered page content. <body>...</body>

Minimal HTML document

This compact document contains the essential structure required for a basic responsive English-language page.

<!doctype html> <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Page title</title></head><body><main><h1>Page heading</h1></main></body></html>

Declare a language change

Use lang on content whose language differs from the document’s primary language.

<p lang="fr">Bonjour tout le monde.</p>

Describe and configure the document

Metadata and the Head

Use head metadata to identify the page, describe its content, connect styles and icons, define canonical URLs, and load scripts.

Common HTML head elements and metadata examples
Markup Purpose Example Copy
<title> Defines the document title shown in browser and bookmark interfaces. <title>HTML Forms: Practical Examples</title>
meta description Provides a concise document description for directories and search interfaces. <meta name="description" content="Learn accessible HTML forms with practical examples.">
meta robots Supplies page-level instructions to supporting search crawlers. <meta name="robots" content="index, follow">
link canonical Identifies the preferred URL for the current document. <link rel="canonical" href="https://example.com/html-guide/">
link stylesheet Loads an external CSS stylesheet. <link rel="stylesheet" href="/assets/site.css">
link icon Associates an icon with the document. <link rel="icon" href="/favicon.svg" type="image/svg+xml">
meta author Provides a free-form author value for the document. <meta name="author" content="Example Editorial Team">
meta theme-color Suggests a color for supporting browser interface elements. <meta name="theme-color" content="#172033">
<script defer> Downloads a classic external script without blocking HTML parsing and runs it after parsing. <script src="/assets/site.js" defer></script>
<script type="module"> Loads a JavaScript module, which is deferred by default. <script type="module" src="/assets/app.js"></script>
link preload Requests early fetching of a resource that the current page will soon use. <link rel="preload" href="/fonts/site.woff2" as="font" type="font/woff2" crossorigin>
<base> Sets the base URL used to resolve relative URLs throughout the document. <base href="https://example.com/docs/">

Social sharing metadata

Open Graph metadata is widely used by social platforms but is not part of the core HTML Standard.

<meta property="og:title" content="HTML Forms Guide">

Responsive viewport

This common setting makes the layout viewport follow the device width while preserving the browser’s default initial zoom.

<meta name="viewport" content="width=device-width, initial-scale=1">

Organize readable content

Headings and Text Content

Structure page topics with meaningful headings and use the appropriate element for paragraphs, quotations, line breaks, preformatted text, and contact information.

HTML elements for headings and text content
Element Purpose Example Copy
<h1> Represents a top-level heading for the page or its relevant context. <h1>Complete HTML Guide</h1>
<h2> Introduces a major subsection beneath the preceding higher-level topic. <h2>Accessible Forms</h2>
<h3>–<h6> Define progressively deeper levels within a section hierarchy. <h3>Email field</h3>
<p> Represents a paragraph of phrasing content. <p>Use semantic HTML to describe content clearly.</p>
<br> Creates a line break where the break is part of the content. First line<br>Second line
<hr> Represents a thematic break between paragraph-level topics. <hr>
<blockquote> Represents a section quoted from another source. <blockquote cite="https://example.com/source"><p>Quoted text.</p></blockquote>
<pre> Preserves whitespace and line breaks as written in the source. <pre>Line 1 Line 2</pre>
<address> Provides contact information for its nearest article or body ancestor. <address><a href="mailto:help@example.com">Email support</a></address>
<hgroup> Groups a heading with secondary content such as a subtitle or tagline. <hgroup><h1>HTML Guide</h1><p>Practical examples for modern websites</p></hgroup>

Logical heading hierarchy

Use heading levels to communicate nesting. A subsection beneath an <h2> normally begins with an <h3>.

<h2>Forms</h2><h3>Labels</h3>

Inline quotation

Use <q> for a short quotation that remains within a paragraph or other phrasing content.

<p>The guide says <q>start with meaning</q>.</p>

Add meaning within text

Text-Level Semantics

Mark importance, emphasis, edits, dates, abbreviations, code, keyboard input, variables, and other meanings within paragraphs and headings.

HTML text-level semantic elements with examples
Element Meaning Example Copy
<strong> Marks strong importance, seriousness, or urgency. <strong>Back up your files first.</strong>
<em> Adds stress emphasis that can change the meaning of a sentence. <p>You should <em>verify</em> the URL.</p>
<b> Draws attention without adding importance or changing voice. <p>Includes <b>free shipping</b> this week.</p>
<i> Marks text in an alternate voice, mood, or conventional category. <p>The term <i>viewport</i> has a specific meaning.</p>
<mark> Highlights text because it is relevant in the current context. <p>Search result: <mark>semantic HTML</mark></p>
<small> Represents side comments such as legal text or disclaimers. <small>Terms and conditions apply.</small>
<s> Marks content that is no longer accurate or relevant. <p><s>$49</s> $29</p>
<del> Represents content removed during an edit. <p>Meeting at <del>10:00</del> 11:00.</p>
<ins> Represents content inserted during an edit. <p>Meeting at <ins>11:00</ins>.</p>
<code> Represents a fragment of computer code. <p>Use the <code>main</code> element.</p>
<kbd> Represents user input, commonly from a keyboard. <p>Press <kbd>Ctrl</kbd>+<kbd>S</kbd>.</p>
<samp> Represents sample output from a program or computing system. <samp>File saved successfully.</samp>
<var> Represents a variable in code or a mathematical expression. <p>Set <var>x</var> to 10.</p>
<sub> / <sup> Marks subscripts and superscripts when required by meaning. H<sub>2</sub>O and x<sup>2</sup>
<time> Represents a date, time, duration, or machine-readable temporal value. <time datetime="2026-08-18">August 18, 2026</time>
<abbr> Represents an abbreviation or acronym. <abbr title="HyperText Markup Language">HTML</abbr>
<cite> Represents the title of a creative work. <cite>The HTML Living Standard</cite>
<data> Associates visible content with a machine-readable value. <data value="SKU-1042">Blue notebook</data>

Code block

Combine <pre> and <code> when whitespace and line breaks are part of a code sample.

<pre><code>const ready = true;</code></pre>

Bidirectional isolation

Use <bdi> to isolate text whose writing direction is unknown, such as a user-provided name in a list.

<p>User: <bdi>إبراهيم</bdi></p>

Embed useful visual content

Images and Responsive Images

Embed images with appropriate text alternatives, reserve layout space, defer off-screen downloads, and provide responsive sources for different viewport sizes or compositions.

HTML image elements and responsive image attributes
Markup Purpose Example Copy
<img> Embeds an image resource in the document. <img src="team.jpg" alt="Support team standing in the office">
alt Provides a text alternative based on the image’s purpose and context. <img src="chart.png" alt="Sales increased from 40 to 65 units">
alt="" Marks an image as decorative so assistive technology can ignore it. <img src="divider.svg" alt="">
width / height Provides intrinsic dimensions so the browser can reserve layout space. <img src="product.jpg" alt="Blue notebook" width="800" height="600">
loading="lazy" Suggests deferring an off-screen image until it approaches the viewport. <img src="gallery-08.jpg" alt="Mountain trail at sunrise" loading="lazy">
decoding="async" Suggests decoding the image asynchronously before presentation. <img src="gallery.jpg" alt="City skyline" decoding="async">
srcset Provides image candidates with their intrinsic widths. <img src="photo-800.jpg" srcset="photo-480.jpg 480w, photo-800.jpg 800w, photo-1200.jpg 1200w" alt="Coastal landscape">
sizes Describes the expected rendered width so a suitable srcset candidate can be selected. <img src="photo-800.jpg" srcset="photo-480.jpg 480w, photo-800.jpg 800w" sizes="(max-width: 600px) 100vw, 800px" alt="Coastal landscape">
<picture> Offers alternative image sources for art direction or format selection. <picture><source media="(max-width: 600px)" srcset="portrait.jpg"><img src="landscape.jpg" alt="Team presenting a project"></picture>
source type Offers an image format that the browser may select when supported. <picture><source srcset="photo.avif" type="image/avif"><source srcset="photo.webp" type="image/webp"><img src="photo.jpg" alt="Forest path"></picture>
<figure> Groups self-contained content that may be referenced from the main text. <figure><img src="diagram.png" alt="Request processing flow"><figcaption>Figure 1: Request flow.</figcaption></figure>
fetchpriority Provides a relative fetch-priority hint for an image. <img src="hero.jpg" alt="HTML code on a laptop screen" fetchpriority="high">

Functional image alternative

When an image is the only content of a link, its alternative text should describe the link’s purpose rather than its appearance.

<a href="/"><img src="logo.svg" alt="Example Company home"></a>

CSS for fluid images

Preserve the image’s aspect ratio while preventing it from exceeding its container.

img { max-width: 100%; height: auto; }

Add time-based and external media

Audio, Video, and Embedded Content

Embed audio and video with controls and alternatives, provide multiple media sources, add timed text tracks, and constrain third-party content loaded through iframes.

HTML audio, video, source, track, and iframe examples
Markup Purpose Example Copy
<audio controls> Embeds audio and exposes browser-provided playback controls. <audio controls src="episode.mp3"></audio>
<video controls> Embeds video and exposes browser-provided playback controls. <video controls src="tutorial.mp4"></video>
<source> Offers alternative media resources and their MIME types. <video controls><source src="tutorial.webm" type="video/webm"><source src="tutorial.mp4" type="video/mp4"></video>
<track kind="captions"> Adds synchronized captions for dialogue and relevant audio information. <track kind="captions" src="captions-en.vtt" srclang="en" label="English" default>
<track kind="subtitles"> Adds translated or transcribed dialogue for users who understand another language. <track kind="subtitles" src="subtitles-es.vtt" srclang="es" label="Español">
poster Provides an image displayed before video playback begins. <video controls poster="tutorial-cover.jpg" src="tutorial.mp4"></video>
preload="metadata" Hints that media metadata should be fetched before playback. <audio controls preload="metadata" src="episode.mp3"></audio>
width / height Provides video dimensions and helps reserve layout space. <video controls width="1280" height="720" src="tutorial.mp4"></video>
<iframe> Embeds another browsing context within the current document. <iframe src="https://example.com/map/" title="Map showing the office location"></iframe>
loading="lazy" Suggests deferring an off-screen iframe until it approaches the viewport. <iframe src="https://example.com/map/" title="Office location map" loading="lazy"></iframe>
sandbox Applies restrictions to content inside an iframe unless selected capabilities are allowed. <iframe src="preview.html" title="Document preview" sandbox></iframe>
allowfullscreen Allows eligible iframe content to request fullscreen presentation. <iframe src="https://example.com/player/" title="Product demonstration" allowfullscreen></iframe>

Video with captions

Place timed text tracks inside the video element after its source elements.

<video controls poster="cover.jpg"><source src="tutorial.mp4" type="video/mp4"><track kind="captions" src="captions-en.vtt" srclang="en" label="English" default></video>

Responsive video sizing

Allow video to shrink within its container while preserving its intrinsic aspect ratio.

video { max-width: 100%; height: auto; }

Group related items

Lists

Use unordered lists for collections without a meaningful sequence, ordered lists for steps or rankings, and description lists for name-and-value groups.

HTML list elements and attributes with examples
Element or attribute Purpose Example Copy
<ul> Contains a list whose item order does not change its meaning. <ul><li>HTML</li><li>CSS</li></ul>
<ol> Contains a list whose item order is meaningful. <ol><li>Create the file</li><li>Add the markup</li></ol>
<li> Represents an item inside an ordered, unordered, or menu list. <li>Accessible labels</li>
start Sets the starting ordinal value of an ordered list. <ol start="5"><li>Fifth item</li></ol>
reversed Numbers an ordered list in descending order. <ol reversed><li>Third place</li><li>Second place</li><li>First place</li></ol>
value Sets the ordinal value of a selected item in an ordered list. <ol><li>First</li><li value="5">Fifth</li></ol>
Nested list Places a complete child list inside its parent list item. <ul><li>Frontend<ul><li>HTML</li></ul></li></ul>
<dl> Contains groups of terms or names and their descriptions or values. <dl><dt>HTML</dt><dd>Structures web content.</dd></dl>
<dt> Represents a term or name within a description list group. <dt>Browser</dt>
<dd> Provides a description or value for preceding terms in the group. <dd>Software that presents web documents.</dd>
<div> in <dl> Groups related terms and descriptions within a description list. <dl><div><dt>Status</dt><dd>Published</dd></div></dl>

Navigation list

A list can communicate the relationship between navigation items, while <nav> identifies the navigation region.

<nav aria-label="Primary"><ul><li><a href="/">Home</a></li><li><a href="/guides/">Guides</a></li></ul></nav>

Change marker appearance with CSS

Keep list meaning in HTML and control marker presentation with CSS.

ul.features { list-style-type: square; }

Represent related data

Tables

Mark up data with explicit rows, header cells, data cells, and a caption so relationships remain understandable visually and through assistive technology.

HTML table elements and attributes with examples
Element or attribute Purpose Example Copy
<table> Represents data arranged in rows and columns. <table>...</table>
<caption> Provides a title or concise description for its table. <caption>Quarterly sales by region</caption>
<thead> Groups rows containing column-heading information. <thead><tr><th scope="col">Product</th></tr></thead>
<tbody> Groups the primary data rows in a table. <tbody><tr><td>Notebook</td></tr></tbody>
<tfoot> Groups summary or footer rows for the table. <tfoot><tr><th scope="row">Total</th><td>125</td></tr></tfoot>
<tr> Represents one row of table cells. <tr><td>Notebook</td><td>$12</td></tr>
<th> Represents a header cell associated with data cells. <th scope="col">Price</th>
<td> Represents a data cell. <td>$12</td>
scope="col" Identifies a header cell that applies to its column. <th scope="col">Status</th>
scope="row" Identifies a header cell that applies to its row. <th scope="row">Basic plan</th>
colspan Makes a cell span a specified number of columns. <th colspan="2">Contact details</th>
rowspan Makes a cell span a specified number of rows. <th rowspan="2" scope="rowgroup">Europe</th>
<colgroup> Groups one or more columns for shared presentation or semantics. <colgroup><col><col class="numeric"></colgroup>

Accessible simple data table

A caption and scoped header cells communicate the table’s topic and basic row-and-column relationships.

<table><caption>Plan prices</caption><thead><tr><th scope="col">Plan</th><th scope="col">Price</th></tr></thead><tbody><tr><th scope="row">Basic</th><td>$9</td></tr></tbody></table>

Responsive table container

Preserve table relationships and allow horizontal scrolling inside a wrapper when the available viewport is too narrow.

.table-wrap { overflow-x: auto; }

Collect structured user input

Forms

Group related controls, provide visible labels and instructions, and submit named values using an appropriate HTTP method and encoding.

HTML form elements and submission attributes with examples
Element or attribute Purpose Example Copy
<form> Groups controls that can submit data to a processing URL. <form action="/subscribe/" method="post">...</form>
<label> Provides a caption associated with a form control. <label for="email">Email address</label><input id="email" name="email" type="email">
<textarea> Creates a multiline text-entry control. <label for="message">Message</label><textarea id="message" name="message" rows="5"></textarea>
<select> Creates a control for choosing from a list of options. <label for="country">Country</label><select id="country" name="country"><option value="us">United States</option></select>
<option> Represents one selectable choice inside a select or datalist. <option value="monthly">Monthly billing</option>
<optgroup> Groups related options under a label. <optgroup label="Europe"><option value="dk">Denmark</option></optgroup>
<button> Creates a button with an explicit submit, reset, or button behavior. <button type="submit">Create account</button>
<fieldset> Groups related form controls and labels. <fieldset><legend>Contact preference</legend>...</fieldset>
<legend> Provides a caption for the controls in its fieldset. <legend>Choose a delivery method</legend>
<datalist> Provides suggestions for a compatible input without restricting entry to those choices. <input name="browser" list="browsers"><datalist id="browsers"><option value="Firefox"><option value="Chrome"></datalist>
<output> Represents the result of a calculation or user action. <output for="quantity price" name="total">$0.00</output>
method="get" Submits form data in the URL query, suitable for retrieval actions such as search. <form action="/search/" method="get">...</form>
method="post" Submits form data in the request body for processing by the server. <form action="/account/" method="post">...</form>
multipart/form-data Sets the encoding required when a POST form uploads files. <form action="/upload/" method="post" enctype="multipart/form-data">...</form>

Radio-button group

Give related radio buttons the same name so only one value from the group can be selected.

<fieldset><legend>Contact method</legend><label><input type="radio" name="contact" value="email"> Email</label><label><input type="radio" name="contact" value="phone"> Phone</label></fieldset>

File upload control

Use a POST form with multipart/form-data and validate every uploaded file on the server.

<label for="resume">Resume</label><input id="resume" name="resume" type="file" accept=".pdf,.doc,.docx">

Choose the correct form control

Input Types

Select an input type that matches the expected value so browsers can provide suitable controls, keyboards, validation behavior, and autofill support.

HTML input types with purposes and examples
Input type Typical use Example Copy
text Single-line text without a more specific semantic type. <input type="text" name="display_name">
email An email address or, with multiple, a list of email addresses. <input type="email" name="email" autocomplete="email" required>
password Text whose value is visually obscured by the user agent. <input type="password" name="password" autocomplete="current-password">
search A single-line field intended for search terms. <input type="search" name="q" aria-label="Search articles">
tel A telephone number, without automatic universal-format validation. <input type="tel" name="phone" autocomplete="tel">
url An absolute URL. <input type="url" name="website" placeholder="https://example.com">
number A numeric value that may have minimum, maximum, and step constraints. <input type="number" name="quantity" min="1" max="20" step="1">
range An imprecise numeric value selected within a range. <input type="range" name="volume" min="0" max="100" value="50">
date A calendar date without a time or timezone. <input type="date" name="start_date">
time A time of day without a timezone. <input type="time" name="appointment_time">
datetime-local A local date and time without a timezone. <input type="datetime-local" name="meeting">
month A year and month value. <input type="month" name="billing_month">
week A week number and week-numbering year. <input type="week" name="delivery_week">
color A color value selected through a supporting browser interface. <input type="color" name="accent" value="#e84a27">
checkbox An independently selected on-or-off option. <label><input type="checkbox" name="updates" value="yes"> Email me updates</label>
radio One choice within a group of controls sharing the same name. <label><input type="radio" name="plan" value="basic"> Basic</label>
file Lets the user select one or more files for submission. <input type="file" name="photos" accept="image/*" multiple>
hidden Submits a value that is not presented as an interactive control. <input type="hidden" name="form_id" value="newsletter-2026">
submit Creates a button that submits its form. <input type="submit" value="Send message">
button Creates a button with no default submission behavior. <input type="button" value="Open preview">

Checkbox group

Multiple checked controls can submit the same field name with different values.

<fieldset><legend>Topics</legend><label><input type="checkbox" name="topics" value="html"> HTML</label><label><input type="checkbox" name="topics" value="css"> CSS</label></fieldset>

Use text for digit strings

Telephone numbers, postal codes, card numbers, and account IDs are identifiers rather than quantities. Use a text-oriented type and an appropriate inputmode when numeric keyboard input helps.

<input type="text" name="postal_code" inputmode="numeric" autocomplete="postal-code">

Guide entry and validate values

Form Attributes and Validation

Provide autofill and keyboard hints, define value constraints, connect instructions to controls, and use browser validation as a usability layer before secure server-side validation.

HTML form attributes for user input and constraint validation
Attribute Purpose Example Copy
name Provides the field name used when the control contributes to form submission. <input type="email" name="email">
required Makes a supporting control invalid when its required value is missing. <input type="email" name="email" required>
minlength Sets the minimum permitted length for user-entered text. <textarea name="message" minlength="20"></textarea>
maxlength Sets the maximum permitted length for user-entered text. <input type="text" name="username" maxlength="30">
min / max Defines the permitted lower and upper bounds for compatible controls. <input type="number" name="guests" min="1" max="12">
step Defines the permitted value interval for compatible numeric or temporal controls. <input type="number" name="price" min="0" step="0.01">
pattern Requires the complete value to match a valid JavaScript regular expression compiled with Unicode Sets mode. <input type="text" name="code" pattern="[A-Z]{3}-[0-9]{4}" title="Three uppercase letters, a hyphen, and four digits">
autocomplete Provides a token describing the field’s expected autofill value. <input type="text" name="full_name" autocomplete="name">
inputmode Hints which virtual keyboard or input interface may be useful. <input type="text" name="verification_code" inputmode="numeric">
placeholder Provides a short hint inside an empty compatible control. <input type="url" name="website" placeholder="https://example.com">
readonly Prevents editing while allowing the control to remain focusable and submitted. <input type="text" name="account_id" value="A-1042" readonly>
disabled Disables interaction; a disabled control does not contribute its value to submission. <input type="text" name="invite_code" disabled>
multiple Allows multiple values for supporting email and file controls. <input type="email" name="recipients" multiple>
accept Hints which file types should be offered by a file picker. <input type="file" name="avatar" accept="image/png,image/jpeg">
aria-describedby Associates a control with additional instructions or an error description. <label for="password">Password</label><input id="password" type="password" aria-describedby="password-help"><p id="password-help">Use at least 12 characters.</p>
novalidate Disables browser constraint validation when the form is submitted. <form action="/register/" method="post" novalidate>...</form>

Username constraint

Explain the rule visibly rather than relying only on a validation message or the title attribute.

<label for="username">Username</label><input id="username" name="username" pattern="[a-z0-9_]{3,20}" aria-describedby="username-help" required><p id="username-help">Use 3–20 lowercase letters, digits, or underscores.</p>

Browser validation CSS

Style invalid user-edited fields carefully and never rely on color alone to communicate an error.

input:user-invalid { border-color: #b42318; }

Describe page regions by meaning

Semantic Page Structure

Use structural elements to identify navigation, dominant content, standalone articles, thematic sections, supporting content, and page-level or article-level headers and footers.

Semantic HTML elements for page structure
Element Meaning Example Copy
<header> Represents introductory or navigational content for its nearest sectioning ancestor. <header><h1>Developer Guides</h1></header>
<nav> Represents a major group of navigation links. <nav aria-label="Primary">...</nav>
<main> Identifies the dominant content associated with the document’s central topic. <main id="main-content">...</main>
<article> Represents self-contained content that could stand independently or be reused. <article><h2>Release notes</h2>...</article>
<section> Represents a thematic grouping of content, typically identified by a heading. <section><h2>Installation</h2>...</section>
<aside> Represents content indirectly related to the surrounding content. <aside aria-labelledby="related-title"><h2 id="related-title">Related guides</h2>...</aside>
<footer> Represents footer information for its nearest sectioning ancestor or body. <footer><p>Updated August 2026.</p></footer>
<address> Provides contact information for the nearest article or document body. <address><a href="mailto:editor@example.com">Contact the editor</a></address>
<div> Provides a generic flow container when no semantic element accurately applies. <div class="card-grid">...</div>

Basic semantic page

This structure exposes a page header, primary navigation, dominant content, supporting content, and page footer.

<header>...</header><nav aria-label="Primary">...</nav><main id="main-content"><article>...</article><aside>...</aside></main><footer>...</footer>

Article with its own header and footer

Header and footer elements can belong to an individual article rather than only to the complete page.

<article><header><h2>Release notes</h2></header><p>...</p><footer><p>Published by the product team.</p></footer></article>

Configure elements consistently

Global Attributes

Global attributes can be used on HTML elements to identify them, assign classes, declare language and direction, control focus or editing, and communicate hidden or inactive state.

Common HTML global attributes with examples
Attribute Purpose Example Copy
id Assigns a document-wide unique identifier to an element. <section id="pricing">...</section>
class Assigns one or more space-separated classifications to an element. <article class="card featured">...</article>
lang Declares the language of an element’s content. <p lang="es">Hola a todos.</p>
dir Declares or automatically determines the directionality of text. <p dir="auto">User-provided text</p>
hidden Indicates that an element is not currently relevant and should not be presented. <div id="success-message" hidden>Saved successfully.</div>
inert Makes an element and its descendants non-interactive and unavailable to focus navigation. <main inert>...</main>
tabindex="0" Adds an appropriate custom interactive element to sequential keyboard focus order. <div role="button" tabindex="0">Custom control</div>
tabindex="-1" Allows programmatic focus without adding the element to sequential keyboard navigation. <div id="error-summary" tabindex="-1">...</div>
contenteditable Makes an element’s content editable by the user. <div contenteditable="true" aria-label="Editable notes">Edit these notes.</div>
spellcheck Hints whether spelling and grammar checking should be enabled. <textarea spellcheck="true"></textarea>
draggable Indicates whether an element may be dragged through the drag-and-drop API. <div draggable="true">Drag item</div>
translate Hints whether an element’s translatable text and attribute values should be translated. <code translate="no">user_profile</code>
title Provides advisory information associated with an element. <abbr title="Cascading Style Sheets">CSS</abbr>
style Applies declarations directly to one element. <p style="color: #172033;">Example text</p>

Multiple classes

Class tokens are separated by spaces and can independently represent a component, variation, or state.

<button class="button button--primary is-loading" type="button">Save</button>

Focus an error summary

A negative tabindex can support deliberate focus management after a form submission without changing normal tab order.

<div id="errors" tabindex="-1" role="alert">Please correct the highlighted fields.</div>

Identify and annotate elements

IDs, Classes, and Data Attributes

Use unique IDs for document relationships and fragment targets, reusable classes for styling and shared behavior, and data-* attributes for page-specific custom data.

HTML ID, class, and custom data attribute patterns
Pattern Purpose Example Copy
Unique ID Identifies one element within the document. <section id="pricing">...</section>
Fragment target Lets a URL fragment navigate to an element with the matching ID. <a href="#pricing">View pricing</a>
Label relationship Connects a label’s for value to a form control’s ID. <label for="customer-email">Email</label><input id="customer-email" name="email" type="email">
Shared class Classifies multiple elements for shared styling or behavior. <article class="card">...</article>
Multiple classes Assigns several independent class tokens to one element. <article class="card card--featured is-active">...</article>
CSS ID selector Selects the element with a matching ID. #pricing { scroll-margin-top: 2rem; }
CSS class selector Selects every element containing a matching class token. .card { border: 1px solid #d9e0ec; }
data-* Stores custom data associated with an element. <button type="button" data-product-id="SKU-1042">Add to cart</button>
Data attribute selector Selects elements according to the presence or value of an attribute. [data-state="open"] { display: block; }
dataset Reads or writes custom data through an element’s DOMStringMap. const productId = button.dataset.productId;
getElementById Returns the element whose ID matches the supplied string. const pricing = document.getElementById("pricing");
querySelector Returns the first element matching a CSS selector. const card = document.querySelector(".card");
querySelectorAll Returns a static NodeList of elements matching a CSS selector. const cards = document.querySelectorAll(".card");

JavaScript behavior hook

A purpose-specific data attribute can identify behavior without coupling JavaScript to presentation classes.

<button type="button" data-menu-toggle aria-expanded="false">Menu</button>

Convert data names to dataset keys

Hyphenated custom names become camel-cased properties: data-product-id becomes dataset.productId.

element.dataset.productId = "SKU-2048";

Create native interactive interfaces

Details, Dialogs, and Interactive Elements

Build disclosures, dialogs, and lightweight popovers with native HTML behavior before adding custom JavaScript widgets.

Native HTML interactive elements and related methods
Markup or method Purpose Example Copy
<details> Creates a disclosure widget whose additional content can be shown or hidden. <details><summary>Shipping information</summary><p>Delivery takes 3–5 days.</p></details>
<summary> Provides the visible caption or legend for its parent details element. <summary>View technical requirements</summary>
open Causes a details or nonmodal dialog element to begin in its open state. <details open><summary>Requirements</summary><p>HTML knowledge is helpful.</p></details>
<dialog> Represents a dialog box or another temporary interactive component. <dialog id="confirm-dialog"><p>Delete this item?</p></dialog>
showModal() Opens a dialog as a modal in the top layer. document.querySelector("#confirm-dialog").showModal();
show() Opens a dialog as nonmodal content. document.querySelector("#help-dialog").show();
close() Closes an open dialog and can optionally set its return value. document.querySelector("#confirm-dialog").close("cancel");
method="dialog" Lets a form button close its containing dialog without submitting data to a server. <form method="dialog"><button value="cancel">Cancel</button><button value="confirm">Confirm</button></form>
popover Makes an element available as top-layer popover content. <div id="help-popover" popover>Helpful information.</div>
popovertarget Associates a button with a popover element in the same tree. <button type="button" popovertarget="help-popover">Show help</button>
popovertargetaction Requests that a target popover be toggled, shown, or hidden. <button type="button" popovertarget="help-popover" popovertargetaction="hide">Close help</button>
:open Selects supported elements that are currently in an open state. details:open { border-color: #e84a27; }

Complete popover

The trigger and popover are connected declaratively without custom JavaScript.

<button type="button" popovertarget="tips">Show tips</button><div id="tips" popover><p>Use semantic HTML first.</p><button type="button" popovertarget="tips" popovertargetaction="hide">Close</button></div>

Modal dialog trigger

Open a modal dialog from a real button and let a dialog form provide its close actions.

<button type="button" id="open-dialog">Delete item</button><dialog id="confirm-dialog"><p>Delete this item?</p><form method="dialog"><button value="cancel">Cancel</button><button value="confirm">Delete</button></form></dialog>

Test HTML in a Safe Preview

Edit the example and select Run preview. Scripts, external resources, forms, and page navigation are blocked inside the sandboxed preview.

Preview

Make content usable by more people

Accessibility Essentials

Start with semantic HTML, logical source order, keyboard access, useful text alternatives, labeled controls, clear headings, and visible focus before adding ARIA.

Essential accessible HTML patterns
Pattern Purpose Example Copy
Document language Helps user agents and assistive technology interpret and pronounce content. <html lang="en">
Logical headings Communicate page hierarchy and support heading-based navigation. <h2>Account settings</h2><h3>Email preferences</h3>
Landmarks Identify major page regions through semantic structural elements. <header>...</header><nav aria-label="Primary">...</nav><main>...</main><footer>...</footer>
Skip link Lets keyboard users bypass repeated navigation and reach the main content. <a href="#main-content">Skip to main content</a>
Visible label Provides an accessible name and a larger activation target for a form control. <label for="email-address">Email address</label><input id="email-address" name="email" type="email">
Informative alt text Communicates the relevant information or function of an image. <img src="chart.png" alt="Revenue increased by 18 percent in 2026">
Decorative image Lets assistive technology ignore an image that adds no information or function. <img src="decorative-wave.svg" alt="">
Native button Provides built-in keyboard, focus, activation, and accessibility behavior. <button type="button">Open filters</button>
aria-labelledby Uses the text of one or more referenced elements as an accessible name. <section aria-labelledby="features-title"><h2 id="features-title">Features</h2>...</section>
aria-describedby Associates an element with additional instructions or descriptive text. <input id="password" type="password" aria-describedby="password-help"><p id="password-help">Use at least 12 characters.</p>
aria-expanded Communicates whether a controlled expandable interface is open or collapsed. <button type="button" aria-expanded="false" aria-controls="filters">Filters</button>
aria-live Requests that supporting assistive technology announce relevant dynamic updates. <p aria-live="polite">3 results found.</p>
Table headers Associate data cells with their row or column headers. <th scope="col">Price</th>
Media captions Provide synchronized dialogue and meaningful audio information for video. <track kind="captions" src="captions-en.vtt" srclang="en" label="English" default>

Visible keyboard focus

Enhance focus appearance without removing the browser’s indicator unless an equally visible replacement is provided.

:focus-visible { outline: 3px solid #2457d6; outline-offset: 3px; }

Accessible icon button

When a button has no visible text, provide a concise accessible name and hide a purely decorative icon from assistive technology.

<button type="button" aria-label="Close dialog"><span aria-hidden="true">×</span></button>

Represent reserved and special text

HTML Entities, Comments, and Special Characters

Use character references when reserved syntax characters must appear as text, and use comments only for non-sensitive source notes.

Common HTML character references and comment syntax
Reference Result or purpose Example Copy
&lt; Represents the less-than character used to begin HTML tags. &lt;
&gt; Represents the greater-than character used to end HTML tags. &gt;
&amp; Represents an ampersand, which begins a character reference. &amp;
&quot; Represents a double quotation mark. &quot;
&apos; Represents an apostrophe or single quotation mark. &apos;
&nbsp; Represents a non-breaking space that prevents a line break at that position. 10&nbsp;GB
&copy; Represents the copyright symbol. &copy; 2026 Example Company
&mdash; Represents an em dash. HTML&mdash;the language of web documents
&#169; Uses a decimal numeric character reference for the copyright symbol. &#169;
&#x00A9; Uses a hexadecimal numeric character reference for the copyright symbol. &#x00A9;
HTML comment Adds a source comment that is not rendered as page content. <!-- Navigation begins here -->
Commented block Temporarily prevents ordinary markup inside the comment from being rendered. <!-- <p>Temporary message</p> -->

Display HTML markup as text

Escape the opening and closing angle brackets so the browser presents the markup instead of interpreting it as an element.

&lt;button type=&quot;button&quot;&gt;Save&lt;/button&gt;

Use UTF-8 for ordinary characters

With UTF-8 declared, characters such as accented letters and many symbols can normally be written directly instead of converted to named references.

<meta charset="utf-8">

Check markup and avoid legacy patterns

Validation, Obsolete Elements, Safety, and FAQ

Validate document structure, replace obsolete presentation markup with semantic HTML and CSS, and treat untrusted content as data rather than executable markup.

Obsolete HTML patterns and modern alternatives
Avoid Why Use instead Copy
<center> Obsolete presentation element. .centered { text-align: center; }
<font> Obsolete element that mixes presentation with document structure. .intro { color: #172033; font: 1.125rem/1.6 system-ui; }
<big> Obsolete presentational element for increasing text size. .lead { font-size: 1.25rem; }
<strike> Obsolete element with unclear editing semantics. <s>No longer accurate</s> or <del>Removed content</del>
<tt> Obsolete element for typographic presentation. <code>npm run build</code>
<acronym> Obsolete element formerly used for acronyms. <abbr title="Web Content Accessibility Guidelines">WCAG</abbr>
<marquee> Obsolete moving-content element with usability and accessibility problems. <p role="status">Shipping is currently delayed.</p>
<frame> / <frameset> Obsolete document-framing elements that create navigation and accessibility problems. <main>...</main>
<applet> Obsolete plugin element for Java applets. <canvas> or standards-based HTML, CSS, and JavaScript
align / bgcolor Obsolete presentational attributes on common elements. .notice { text-align: center; background-color: #fff4ef; }
Untrusted innerHTML Can interpret attacker-controlled strings as active markup. output.textContent = userProvidedText;
Missing button type A button associated with a form may submit it unexpectedly. <button type="button">Open preview</button>

What is HTML?

HTML is the markup language used to describe the structure and semantics of web documents. CSS controls presentation, while JavaScript can add behavior.

Is HTML a programming language?

HTML is generally classified as a markup language. It describes elements and relationships rather than expressing general-purpose algorithms.

Are closing tags always required?

Void elements such as <img>, <input>, <br>, and <meta> must not have end tags. Some other end tags may be omitted under specific parsing rules, but explicit markup is often easier to review and maintain.

Can several elements use the same ID?

No. An ID value must be unique within its document. Duplicate IDs can break fragment navigation, labels, ARIA relationships, CSS targeting, and JavaScript selection.

Does valid HTML guarantee accessibility?

No. Validation catches many structural and conformance errors, but accessibility also requires appropriate semantics, alternatives, labels, keyboard behavior, focus management, readable content, contrast, and user testing.

How should HTML be validated?

Validate the complete rendered document, review every reported error in context, test keyboard and assistive-technology behavior, and check the page in the browsers and devices your audience uses.