Why this matters
Before a browser can style or animate anything, it has to know what your page contains. HTML supplies that information. When you write a heading, a list, or a button, you are telling the browser and every assistive tool what each piece of content actually is. Get this layer right and everything you build on top of it becomes easier.
You need HTML because search engines and screen readers depend on it. A page made entirely of generic containers may look fine but reads as a wall of text to a screen reader. Semantic HTML fixes that at no extra cost, and it is the reason a little careful markup pays off far more than clever styling tricks later on.
The big picture
Think of HTML as a set of nested boxes described with tags, not as a list of instructions. You do not tell the browser how to assemble the page step by step. You describe what the finished page means, and the browser works out the rest. That is what declarative means: you state the result you want.
As the browser reads your file, it builds a tree called the Document Object Model, or DOM. Every element becomes a node with parents, children, and attributes. CSS and JavaScript both work by walking this tree. If you picture the DOM as a family tree of elements, most of web development suddenly makes sense.
Core ideas
Elements and tags
An element is an opening tag, some content, and a closing tag. The tag name tells the browser what kind of thing it is. A paragraph uses p, a link uses a, and a block of navigation uses nav. Most elements come in pairs, and whatever sits between the tags belongs to that element.
Some elements have no content and therefore no closing tag. These are void elements, and img, br, input, and meta are common examples. You write them once and the browser understands they are complete. Closing a void element is harmless in HTML5 but entirely unnecessary.
<p>This is a paragraph.</p>
<br>
<img src="cat.png" alt="A cat">
<input type="text" disabled>
Watch out. Wrapping a void element in a closing tag, as in <img></img>. Void elements are self-contained, so just write <img>.
Attributes
Attributes are extra information placed inside an opening tag. They take the form name equals value and describe properties of the element. A link uses href for its destination, an image uses src for its file and alt for its text description, and an input uses type for the kind of control.
Boolean attributes such as disabled or required need no value; their presence alone means on. Global attributes like id, class, and title work on almost every element. An id must be unique on the page, while a class can be shared by many elements and is what CSS and JavaScript usually target.
<a href="/about" title="About us">About</a>
<input id="email" type="email" required>
<div class="card" data-id="42">Card</div>
Watch out. Reusing the same id on two elements. Use a class when several elements share a style or behaviour.
The document skeleton
Every page starts with a doctype declaration that tells the browser to use standards mode. Below it sits the html element, which contains a head and a body. The head holds metadata: the title shown in the tab, the character encoding, and links to stylesheets.
The body holds everything the visitor sees. Keeping this structure consistent matters because the browser relies on it. Forgetting the charset meta tag can turn carefully typed punctuation into gibberish on some systems, so include it as a matter of habit.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Page</title>
</head>
<body>
<p>Hello</p>
</body>
</html>
Watch out. Putting visible content in the head. Text belongs in the body; the head is for metadata only.
Semantic elements
HTML gives you elements that describe purpose, not just appearance. The header, nav, main, article, section, aside, and footer elements each carry meaning. Choosing them makes your document readable by machines and by people who use assistive technology.
A common pattern is one main element per page, with articles inside it and a nav for site links. This does not change how the page looks by default, but it gives every region a role. It also makes your own code far easier to navigate months later.
<header><h1>Site</h1></header>
<nav><a href="/">Home</a></nav>
<main>
<article><h2>Post</h2></article>
<aside>Related links</aside>
</main>
<footer>Copyright</footer>
Watch out. Reaching for a div for every container. If an element with a clear meaning exists, prefer it over a generic div.
Text, links, and images
Headings run from h1 to h6 and should describe a hierarchy, not a font size. Use one h1 for the main topic and let h2 and h3 break it down. Paragraphs use p, and inline emphasis uses strong or em depending on whether you mean importance or stress.
Links use the a element with an href, and images use img with a src and an alt. The alt text should describe the image for someone who cannot see it. If the image is purely decorative, an empty alt tells screen readers to skip it entirely.
<h1>Daily notes</h1>
<p>Read the <a href="/guide">guide</a> first.</p>
<img src="logo.png" alt="Company logo" width="120">
<img src="divider.png" alt="">
Watch out. Writing alt='image' for every picture. Describe the content, not the file type, or leave it empty for decoration.
Forms and inputs
Forms collect information. A form element wraps inputs, and each input needs a name so its value can be submitted. The type attribute picks the right control: text, email, password, checkbox, and so on. The browser uses it to validate entries and to show the right keyboard on phones.
Every input should have a matching label whose for attribute equals the input id. That connection lets a screen reader announce the field and lets a click on the label focus the input. It is a small habit with a large accessibility payoff.
<form action="/signup" method="post">
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<button type="submit">Join</button>
</form>
Watch out. Using a placeholder instead of a label. Placeholders vanish as soon as typing starts; labels do not.
Markup becomes a tree
When the browser parses your file it creates a DOM tree. Each element is a node, and nested elements become its children. The parser is forgiving: it will close missing tags and rearrange broken markup rather than stop and show an error.
That forgiveness is a double-edged sword. Because the browser repairs markup silently, two slightly different files can produce different trees. Validating your markup and nesting tags properly keeps the tree predictable, which matters when CSS and JavaScript rely on its shape.
Watch out. Assuming the browser preserves exactly what you write. It corrects malformed markup, so always nest and close tags correctly.
Reusable structure
HTML has no functions, loops, or variables. You cannot write a reusable unit of markup in HTML alone, because markup is declarative: it describes one document, not a procedure for building documents. Any claim otherwise is a misunderstanding of what the language does.
Reuse in real projects therefore comes from other places. Semantic elements give you reusable patterns, the template element holds inert markup you can clone, and Web Components let you define custom elements with their own behaviour. JavaScript ties it together. HTML's job is to describe structure honestly.
Declarative by design
Because HTML is a description rather than a program, there is nothing to call or invoke. You repeat a block by writing it again, or you let another layer generate it for you. Understanding this early saves you from hunting for HTML functions that simply do not exist.
Semantic patterns
Reuse often starts with convention. If every card is an article with a header and a footer, you have an informal component that humans and tools can recognise. Pair it with a class and your CSS can style all of them at once.
<article class="card">
<header><h2>Title</h2></header>
<p>Body text</p>
<footer>Posted today</footer>
</article>
The template element
The template element stores markup that is parsed but not rendered. You can keep one card structure in the page and clone it with JavaScript whenever you need another. This keeps your structure in HTML, where it belongs, instead of buried in strings.
<template id="card">
<article class="card"><h2></h2></article>
</template>
<script>
const t = document.getElementById('card');
document.body.appendChild(t.content.cloneNode(true));
</script>
Custom elements
Web Components let you define your own tag, such as user-card, backed by a JavaScript class. Once registered, the tag behaves like a built-in element and can be dropped in anywhere. This is the closest HTML ever gets to a reusable component.
<script>
class UserCard extends HTMLElement {
connectedCallback() {
this.textContent = 'Ada Lovelace';
}
}
customElements.define('user-card', UserCard);
</script>
<user-card></user-card>
Shadow DOM and slots
A custom element can attach a shadow root, a private DOM tree that outside styles do not leak into. Slots let you pass content from the main document into that private tree, so one component can wrap arbitrary markup supplied by whoever uses it.
<script>
const host = document.querySelector('user-card');
const root = host.attachShadow({ mode: 'open' });
root.innerHTML = '<strong>Card:</strong> <slot></slot>';
</script>
Behaviour comes from JavaScript
Every interactive effect on the web is JavaScript listening for events and changing the DOM. HTML marks up the starting state and JavaScript updates it in response. Keeping that boundary clear makes both layers much easier to reason about and debug.
<button id="more">Show more</button>
<script>
document.getElementById('more').addEventListener('click', () => {
document.body.insertAdjacentHTML('beforeend', '<p>More!</p>');
});
</script>
Function reference
These are the functions you will reach for most often. Each one is shown with its syntax, its inputs and outputs, a working example, and the mistakes to avoid.
<template>
Declarative mechanism
A template keeps a piece of markup ready without showing it. The browser parses the contents but leaves them inert until JavaScript clones and inserts them.
| Syntax | <template id="row">...markup...</template> |
|---|---|
| Parameters | id — A name JavaScript uses to find the template. |
| Returns | The element itself renders nothing; its content becomes live only when you clone it. |
<template id="row">
<li class="item">New item</li>
</template>
<script>
const tpl = document.querySelector("#row");
document.querySelector("ul").appendChild(tpl.content.cloneNode(true));
</script>
What you can do with it. Store a markup pattern you repeat, like list rows or cards. Build a small component library without a framework. Keep HTML structure in HTML instead of generating it with string concatenation.
Choose it when. Choose <template> when you need reusable markup that stays hidden until JavaScript activates it, rather than writing the same tags over and over in your HTML. Remember that HTML only describes structure; behaviour always comes from JavaScript.
| Mistake | Fix |
|---|---|
| Putting a template's content directly on the page and expecting it to appear. | Templates are inert by design; clone template.content with JavaScript. |
| Editing the template in place instead of cloning it. | Clone first, then change the copy, so the original stays reusable. |
customElements.define()
Declarative mechanism
This browser API registers a new HTML tag backed by a JavaScript class. Once registered, you can use your custom tag in markup just like any built-in element.
| Syntax | customElements.define(name, class) |
|---|---|
| Parameters | name — The tag name; it must contain a hyphen, such as user-card. class — A class extending HTMLElement that defines behaviour. |
| Returns | Registers the element and returns undefined; the class becomes usable as a new tag. |
<script>
class UserCard extends HTMLElement {
connectedCallback() {
this.textContent = "Hello from a custom element";
}
}
customElements.define("user-card", UserCard);
</script>
<user-card></user-card>
What you can do with it. Create self-contained widgets such as a rating control or a modal. Encapsulate behaviour behind a familiar HTML-like tag. Share components across pages without a build step.
Choose it when. Choose customElements.define when you want a reusable tag with its own JavaScript behaviour, rather than attaching scripts to ordinary divs by hand. This is a browser API, not an HTML function.
| Mistake | Fix |
|---|---|
| Naming a custom element without a hyphen. | Include a hyphen, for example user-card, so it cannot clash with standard tags. |
| Registering the same tag name twice. | Call define once per name and guard with customElements.get if unsure. |
<slot>
Declarative mechanism
A slot is a placeholder inside a shadow DOM that lets you pass markup into a custom element. It decides where the caller's content appears inside the component.
| Syntax | <slot name="title">Fallback content</slot> |
|---|---|
| Parameters | name — Matches an element's slot attribute to route content to this slot. |
| Returns | No value; it projects the page's child elements into a named spot in the shadow tree. |
<my-box>
<h2 slot="title">Hi</h2>
<p>Body text</p>
</my-box>
<script>
class MyBox extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: "open" }).innerHTML =
'<slot name="title"></slot><slot></slot>';
}
}
customElements.define("my-box", MyBox);
</script>
What you can do with it. Let callers supply a title and body to a reusable card component. Provide default content that shows when nothing is passed in. Build layout wrappers with flexible inner content.
Choose it when. Choose <slot> when a custom element should accept content from the page that uses it, rather than hard-coding every variation inside the component.
| Mistake | Fix |
|---|---|
| Forgetting to attach a shadow root, so slots do nothing. | Call attachShadow first and place the slot markup inside the shadow root. |
| Mismatched slot names between the attribute and the slot element. | Use the exact same name in the slot attribute and the slot's name attribute. |
data-* attributes
Declarative mechanism
data-* attributes let you attach your own private data to an element without misusing standard attributes. Scripts can read and write that data through the dataset property.
| Syntax | data-user-id="42" |
|---|---|
| Parameters | * — Any lowercase name you choose after the data- prefix. |
| Returns | Nothing is returned by the markup; scripts read values as element.dataset.userId. |
<div class="card" data-user-id="42" data-state="active">Card</div>
<script>
const card = document.querySelector(".card");
console.log(card.dataset.userId);
card.dataset.state = "closed";
</script>
What you can do with it. Store an id that JavaScript uses when a button is clicked. Keep small state flags next to the element they describe. Pass configuration from server-rendered HTML into a script.
Choose it when. Choose data-* when you need to tuck a small piece of information onto an element for JavaScript, rather than adding hidden inputs or global variables.
| Mistake | Fix |
|---|---|
| Using a custom attribute without the data- prefix. | Prefix it, such as data-user-id, so it stays valid and accessible via dataset. |
| Expecting hyphenated names to stay hyphenated in JavaScript. | data-user-id becomes dataset.userId in camelCase. |
<label>
Declarative mechanism
A label gives a form control a human-readable name and a clickable area. Linking it to an input improves accessibility and lets a click on the text focus the field.
| Syntax | <label for="email">Email address</label> |
|---|---|
| Parameters | for — The id of the control this label describes. |
| Returns | No value; it associates text with a form control for users and assistive technology. |
<form>
<label for="email">Email address</label>
<input id="email" name="email" type="email" required>
</form>
What you can do with it. Name inputs so screen readers announce them correctly. Give users a bigger click target by clicking the label text. Replace placeholder-only forms with persistent, accessible labels.
Choose it when. Choose <label> for every text field, checkbox, and radio button, rather than relying on nearby text or placeholders to explain the control.
| Mistake | Fix |
|---|---|
| Using a placeholder as the only label. | Add a real label with a for attribute; placeholders vanish once typing starts. |
| Mismatched for and id values. | Make the label's for exactly equal to the input's id. |
<form>
Declarative mechanism
A form groups controls that collect user input and submits their values to a server. It also provides built-in validation before the data is sent.
| Syntax | <form action="/signup" method="post">...controls...</form> |
|---|---|
| Parameters | action — The URL that receives the submitted data. method — The HTTP method, usually get or post. |
| Returns | No value; on submit it packages named controls into a request to the action URL. |
<form action="/signup" method="post">
<label for="name">Name</label>
<input id="name" name="name" required>
<button type="submit">Join</button>
</form>
What you can do with it. Build login and signup screens. Collect a search query and send it to a results page. Let the browser validate required fields and email formats for free.
Choose it when. Choose <form> whenever you collect input from a user, rather than wiring up individual inputs and reading their values by hand.
| Mistake | Fix |
|---|---|
| Forgetting the name attribute on an input. | Add name so the value is included in the submitted data. |
| Expecting submission without a submit button or event handler. | Include a type='submit' button or handle the submit event in JavaScript. |
<picture>
Declarative mechanism
A picture element lets the browser pick the best image from several sources based on screen width or format support. It gives you responsive images without JavaScript.
| Syntax | <picture><source srcset="..."><img src="..." alt="..."></picture> |
|---|---|
| Parameters | srcset — Candidate image files with optional width or density descriptors. media — A media query deciding when a source applies. type — The MIME type so the browser can skip formats it cannot display. |
| Returns | No value; the browser renders the single img that best matches the current context. |
<picture>
<source srcset="hero.webp" type="image/webp">
<source srcset="hero.jpg" type="image/jpeg">
<img src="hero.jpg" alt="A mountain at sunrise">
</picture>
What you can do with it. Serve smaller images to phones to speed up pages. Provide modern formats like WebP with a JPEG fallback. Crop a portrait image differently on narrow screens.
Choose it when. Choose <picture> when you need art direction or format fallback for images, rather than relying on CSS alone to resize a single file.
| Mistake | Fix |
|---|---|
| Omitting the fallback img inside picture. | Always include an img; it is the element that displays and carries the alt text. |
| Putting alt text on source instead of img. | Keep alt on the img element. |
<details>
Declarative mechanism
Details creates a disclosure widget that the user can open and close. It provides show-and-hide behaviour with no JavaScript and works with the keyboard.
| Syntax | <details><summary>Title</summary>Content</details> |
|---|---|
| Parameters | open — A boolean that makes the widget start expanded. |
| Returns | No value; the browser toggles visibility and updates the open attribute as the user interacts. |
<details>
<summary>Shipping details</summary>
<p>Orders arrive in three to five days.</p>
</details>
What you can do with it. Build FAQ lists with expandable answers. Hide advanced options until someone wants them. Show extra metadata under a short summary line.
Choose it when. Choose <details> for simple show/hide content, rather than writing your own accordion with click handlers.
| Mistake | Fix |
|---|---|
| Nesting content directly without a summary. | Add a summary element as the first child to label the toggle. |
| Adding JavaScript to toggle a class when the element already does it. | Use the built-in open state and the toggle event instead. |
<dialog>
Declarative mechanism
Dialog represents a modal window or pop-up that sits above the rest of the page. The browser handles focus trapping, the backdrop, and the Escape key for you.
| Syntax | <dialog id="modal">...content...</dialog> |
|---|---|
| Parameters | open — A boolean that shows the dialog when present. |
| Returns | No value; scripts call showModal() or close() to control it and can read a return value. |
<dialog id="modal">
<p>Save your changes?</p>
<button onclick="document.querySelector('#modal').close()">OK</button>
</dialog>
<script>
document.querySelector("#modal").showModal();
</script>
What you can do with it. Ask for confirmation before deleting something. Show a login or settings panel over the current page. Display a short announcement that dims the background.
Choose it when. Choose <dialog> when you need a real modal with accessibility behaviour built in, rather than a positioned div you manage yourself.
| Mistake | Fix |
|---|---|
| Adding the open attribute directly and expecting a modal backdrop. | Call showModal() so the dialog becomes a true modal with a backdrop. |
| Building a modal from a div without keyboard handling. | Use dialog to get Escape-to-close and focus management for free. |
<meta charset>
Declarative mechanism
This meta tag tells the browser which character encoding the file uses. Setting it to utf-8 lets one page correctly show text from many languages and symbols.
| Syntax | <meta charset="utf-8"> |
|---|---|
| Parameters | charset — The encoding name; utf-8 is the right choice for modern pages. |
| Returns | No value; it instructs the browser how to decode the bytes of the document. |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My page</title>
</head>
<body>
<p>Cafe and 日本語 render correctly.</p>
</body>
</html>
What you can do with it. Display accented letters and emoji without mojibake. Make pages work for international audiences. Ensure form submissions preserve the characters users typed.
Choose it when. Choose <meta charset> in every document head, as a basic correctness step rather than an optional extra.
| Mistake | Fix |
|---|---|
| Placing the charset tag deep in the body. | Put it as the first element inside head so the browser decodes the whole file correctly. |
| Using an old encoding such as ISO-8859-1 by habit. | Use utf-8 for new pages so every character is covered. |
<link rel=stylesheet>
Declarative mechanism
This tag attaches an external CSS file to the page. Keeping styles in a separate file lets many pages share one source of truth for their appearance.
| Syntax | <link rel="stylesheet" href="styles.css"> |
|---|---|
| Parameters | rel — Set to stylesheet to say this file contains styles. href — The path to the CSS file. |
| Returns | No value; the browser fetches the file and applies its rules to the document. |
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
</head>
What you can do with it. Share one stylesheet across an entire site. Load a theme or print stylesheet conditionally. Keep page markup readable by moving style rules out of it.
Choose it when. Choose a linked stylesheet when several pages need the same rules, rather than repeating style blocks or inline styles on every element.
| Mistake | Fix |
|---|---|
| A wrong href path that leads to a missing stylesheet. | Check the relative path from the HTML file and watch the browser console. |
| Putting the link tag in the body. | Place stylesheet links inside head so styles apply before the page renders. |
querySelector()
Declarative mechanism
This browser API finds the first element matching a CSS selector. It is the bridge that lets JavaScript read and change the markup you wrote in HTML.
| Syntax | document.querySelector(selector) |
|---|---|
| Parameters | selector — A CSS selector string such as .card or #email. |
| Returns | The first matching element, or null when nothing matches. |
<p class="note">Hello</p>
<script>
const note = document.querySelector(".note");
note.textContent = "Updated by JavaScript";
</script>
What you can do with it. Grab an element so you can change its text or classes. Attach an event listener to a specific button. Read a value from the first matching form field.
Choose it when. Choose querySelector to reach into your HTML from JavaScript. The HTML only describes structure; this API and scripts like it provide the behaviour.
| Mistake | Fix |
|---|---|
| Forgetting that querySelector returns only the first match. | Use querySelectorAll when you need every matching element. |
| Calling a method on the result without checking for null. | Check that the element exists first, since a missing selector returns null. |
Common mistakes here
| Mistake | Fix |
|---|---|
| Searching for a way to define a function in HTML. | HTML is declarative and has no functions. Put logic in JavaScript. |
| Duplicating a complex card by hand across twenty pages. | Use a template or a custom element and generate the copies. |
| Using a div for every element, even navigation and headings. | Choose the semantic element that matches the content's role. |
| Assuming HTML or CSS can react to a click. | Add an event listener in JavaScript to change state. |
| Cloning a template by appending the template element itself. | Clone template.content, which holds the inert nodes. |
The example, line by line
Here is a small but complete page that puts the document skeleton, metadata, and semantic regions together.
| Code | What it does |
|---|---|
1<!DOCTYPE html> | Declares the document type so the browser uses modern standards mode. |
2<html lang="en"> | Opens the root element and declares English as the document language. |
3<head> | Starts the head, which holds metadata rather than visible content. |
4 <meta charset="utf-8"> | Sets the character encoding so characters render correctly everywhere. |
5 <title>My first page</title> | Sets the title shown in the browser tab and search results. |
6</head> | Closes the head before the visible body begins. |
7<body> | Opens the body, the container for everything the visitor can see. |
8 <header><h1>Code Daily</h1></header> | Adds a header containing the page's top-level heading. |
9 <main> | Opens main, marking the primary content of the page. |
10 <article> | Opens an article, a self-contained piece of content. |
11 <h2>Hello, web</h2> | Adds a second-level heading for this article. |
12 <p>HTML gives this text structure.</p> | Adds a paragraph of body text inside the article. |
13 </article> | Closes the article element. |
14 </main> | Closes the main element. |
15 <footer><p>© 2026</p></footer> | Adds a footer with a copyright paragraph using an entity for the symbol. |
16</body> | Closes the body element. |
17</html> | Closes the html element and completes the document. |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My first page</title>
</head>
<body>
<header><h1>Code Daily</h1></header>
<main>
<article>
<h2>Hello, web</h2>
<p>HTML gives this text structure.</p>
</article>
</main>
<footer><p>© 2026</p></footer>
</body>
</html>
Worked variations
A blog index
Articles nest naturally. Wrap each post in an article with its own heading and a link, and place the whole list inside main. This is a pattern you will reuse constantly, and it reads well to both people and machines.
<main>
<h1>Recent posts</h1>
<article>
<h2><a href="/post-1">Learning HTML</a></h2>
<p>A short introduction.</p>
</article>
<article>
<h2><a href="/post-2">Learning CSS</a></h2>
<p>Making it look good.</p>
</article>
</main>
A labelled fieldset
Related form controls belong inside a fieldset with a legend. The legend describes the group, which helps screen reader users understand that the radio buttons are alternatives rather than unrelated choices.
<fieldset>
<legend>Contact preference</legend>
<label><input type="radio" name="via" value="email"> Email</label>
<label><input type="radio" name="via" value="phone"> Phone</label>
</fieldset>
Common mistakes
| Mistake | Fix |
|---|---|
| Nesting a block element inside a paragraph. | Close the paragraph before opening the block element. |
| Skipping heading levels because of their default size. | Use headings in order and control size with CSS. |
| Omitting alt text to save time. | Write a short description, or use alt='' for decoration. |
| Using <b> and <i> for meaning rather than appearance. | Use strong and em, and style them with CSS. |
| Forgetting the lang attribute on the html element. | Set lang so screen readers choose the right voice. |
Practice
- Write a minimal page with a doctype, head, title, and body containing one paragraph.
- Add a header, main, and footer, and place your paragraph inside an article in main.
- Add a navigation menu with three links inside a nav element.
- Build a signup form with an email field, a labelled checkbox, and a submit button.