Chapter 2: HTML Document Structure and Semantics#
Every website you have ever visited — from a simple blog to a huge social network — starts as a plain text file written in HTML. This chapter shows you exactly how that file is built, piece by piece, so you can create pages that are clear, accessible, and meaningful to both browsers and people.
The Big Picture#
Think of HTML as the skeleton of a web page. It gives the page its basic shape and structure: where the navigation goes, which text is a main heading, where images and forms appear, and how all the pieces relate to each other. In this chapter we will learn the anatomy of a valid HTML document, how to write clean, semantic markup, and how to use the core building blocks — text, links, images, tables, forms, and more — to construct a real, structured web page. By the end, you will see HTML not as a jumble of angle brackets, but as a powerful, readable language for describing content.
The Skeleton of a Web Page: DOCTYPE and the Global Structure#
Every web page follows a simple, unchanging shape. Open any plain text editor and you can type it out in seconds:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My First Page</title>
</head>
<body>
<h1>Hello, world!</h1>
<p>This is a paragraph.</p>
</body>
</html>Let’s take this skeleton apart.
The very first line is the DOCTYPE declaration. It is not an HTML tag; it is a special instruction that tells the browser, “Show this page using the latest web standards.” Without a correct DOCTYPE, browsers switch to quirks mode, which copies the old, buggy way of showing pages from the 1990s. We never want that. Writing <!DOCTYPE html> (the simplest, lowercase form) is all you need to keep things predictable.
After the DOCTYPE, the entire page lives inside a pair of <html> tags. Everything inside them is HTML. A good habit is to include the lang attribute (lang="en" for English), which helps screen readers and search engines understand the language of the content.
An HTML document splits into two major parts:
<head>— a container for invisible information about the page. It holds the title, metadata, links to stylesheets, and scripts that should load early. Nothing inside the<head>appears on the screen (except the title in the browser tab).<body>— the container for all visible content: text, images, forms, videos, and everything the user actually sees and interacts with.
This nested structure — <html> wraps <head> and <body>, and both can contain many child elements — is called hierarchical nesting. Think of it like a family tree: a parent element contains child elements, which can have their own children. It’s important to nest tags correctly: close them in the opposite order you opened them.
HTML element: A unit of content defined by a start tag, optional content, and an end tag (or a self-closing tag). Example:
<p>Hello</p>. Attribute: Extra information placed inside a start tag that modifies an element, likelang="en"orclass="highlight".
With this basic structure in place, the page is ready to hold real content.
📝 Section Recap: Every HTML document begins with
<!DOCTYPE html>and contains a<head>for metadata and a<body>for visible content, all wrapped in an<html>element with proper nesting.
What Goes in the <head>: Title, Metadata, and More#
The <head> section might be invisible, but it is where you set important information that browsers, search engines, and social media platforms rely on.
The most familiar — and required — element is the <title>. The text you put between <title> and </title> appears in the browser’s tab, bookmark name, and search engine result. A good title is short, descriptive, and unique to the page.
Next, we tell the browser which character encoding to use. The most common is UTF-8, which covers almost every alphabet and symbol on the planet:
<meta charset="UTF-8">This <meta> tag sits near the top of the <head>. Without it, special characters (like é, —, or ✓) may turn into gibberish.
Another important meta tag is the viewport setting, which helps mobile devices show the page at a proper scale instead of shrinking a desktop layout to fit:
<meta name="viewport" content="width=device-width, initial-scale=1.0">Other meta tags can give a description for search engines (<meta name="description" content="...">), keywords, or author information. These do not guarantee higher rankings, but they can improve how your page appears in search results.
You will also see <link> elements in the <head> to link to outside files like CSS stylesheets and favicons. We will explore those in later chapters on styling.
📝 Section Recap: The
<head>holds the<title>, character encoding, viewport settings, and other metadata — invisible directions that make the page display correctly everywhere.
Writing Your Content: Headings, Paragraphs, and Text Semantics#
Now we step into the <body> — the part the user sees. The most basic tools are headings and paragraphs.
HTML gives us six levels of headings: <h1> through <h6>. They form an outline for the page, not just different font sizes. Use <h1> for the main title of the page (usually one per page), <h2> for major section titles, and so on. Don’t skip heading levels just to get bigger text; that messes up the page’s structure and confuses screen readers.
A paragraph is a block of text wrapped in <p> tags. Browsers automatically add space before and after paragraphs.
To force a line break inside a paragraph (for a poem or an address), use the self-closing <br> tag.
Inline tags add meaning to bits of text without breaking the flow:
<strong>— marks text as important, usually bold.<em>— marks text with emphasis when spoken, usually italic.<small>— indicates small notes or legal text.<mark>— marks text as highlighted.<code>— displays computer code.
For example:
<p>This is <strong>urgent</strong> and this word is <em>emphasized</em>.</p>A browser styles them differently, but the real power is that search engines and assistive technologies understand the meaning, not just the look.
Block-level element: An element that starts on a new line and takes up the full width available (e.g.,
<p>,<h1>).
Inline element: An element that stays within the flow of text (e.g.,<strong>,<a>,<img>).
📝 Section Recap: Headings provide a document outline, paragraphs hold text blocks, and inline semantic tags add meaning and emphasis to words — helping both people and machines understand your content.
Lists: Ordered, Unordered, and Definition#
When you need to present groups of items, lists keep things tidy. HTML offers three main types.
Unordered lists (<ul>) show bullet points. Each item is a <li>:
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>Ordered lists (<ol>) display items with numbers, letters, or Roman numerals. The browser counts for you:
<ol>
<li>Preheat the oven.</li>
<li>Mix ingredients.</li>
<li>Bake for 20 minutes.</li>
</ol>Definition lists (<dl>) are for term–description pairs, like a glossary. They use <dt> (term) and <dd> (description):
<dl>
<dt>HTML</dt>
<dd>HyperText Markup Language, the standard for web pages.</dd>
<dt>CSS</dt>
<dd>Cascading Style Sheets, used for visual styling.</dd>
</dl>You can put lists inside lists to make sub-items, but always close the inner list before adding more to the outer one.
📝 Section Recap:
<ul>creates bulleted lists,<ol>creates numbered lists, and<dl>pairs terms with definitions — each giving structure to groups of related items.
Connecting Pages: Hyperlinks#
The “H” in HTML — HyperText — comes to life with the anchor element, <a>. It turns any piece of content (text, an image, even a button) into a clickable link.
The most important attribute is href, which holds the destination. It can be:
- An absolute URL to a different website:
href="https://example.com" - A relative path to another page on the same site:
href="about.html"orhref="../contact.html" - A link to a section within the same page:
href="#section-name" - An email link:
href="mailto:someone@example.com"
A simple text link looks like this:
<a href="https://developer.mozilla.org">MDN Web Docs</a>By default, a link opens in the same browser tab. To open in a new tab (only when it really helps), use target="_blank". For security and performance, also add rel="noopener noreferrer":
<a href="https://example.com" target="_blank" rel="noopener noreferrer">Visit Example</a>The rel attribute describes the relationship between the current page and the linked resource. The values noopener and noreferrer prevent the new page from accessing the original page’s window object and hide the referrer information — a good safety practice.
Links are what connect the web together. Use clear, descriptive link text so that screen reader users understand where each link goes.
📝 Section Recap: Use
<a>withhrefto create hyperlinks; manage how links open withtargetand protect privacy withrelattributes.
Adding Images and Video#
Pages come alive with multimedia.
Images#
The image element (<img>) is a self-closing tag that puts a picture on the page. Two attributes are necessary:
src— the path to the image filealt— a short description for anyone who cannot see the image (screen readers, slow connections, or broken links)
<img src="sunset.jpg" alt="A golden sunset over calm ocean water">The alt text is not optional for important images. It makes your content accessible and helps search engines understand the image. If an image is just for decoration, use alt="" so screen readers skip it.
You can also set width and height attributes (values in pixels) to help the browser set aside space before the image loads, so the page doesn’t jump around.
Video#
You add video with the video element (<video>). Unlike <img>, <video> usually contains one or more <source> elements to offer the same video in different formats, because browsers can play different types.
<video controls width="640">
<source src="demo.mp4" type="video/mp4">
<source src="demo.webm" type="video/webm">
Sorry, your browser does not support this video.
</video>The controls attribute shows a play/pause button and a progress bar. The text between the opening and closing <video> tag appears only if the browser cannot play the video at all.
Always include multiple formats (such as MP4 and WebM) to cover the widest range of browsers. The browser picks the first one it understands.
📝 Section Recap: Use
<img>withsrcand meaningfulalttext for accessible images; use<video>with multiple<source>elements to ensure broad video playback support.
Data in Tables#
When you need to present structured data — a schedule, a comparison chart, financial figures — HTML tables are the right tool. (For layout, modern CSS is a far better choice.)
A table is built from a grid of rows and cells:
<table>wraps the whole table.<tr>defines a table row.<th>defines a header cell (bold and centred by default).<td>defines a standard data cell.
A simple table:
<table>
<tr>
<th>Planet</th>
<th>Diameter (km)</th>
</tr>
<tr>
<td>Earth</td>
<td>12,742</td>
</tr>
<tr>
<td>Mars</td>
<td>6,779</td>
</tr>
</table>For larger tables, you can group rows using <thead>, <tbody>, and <tfoot> to give meaning to the rows:
<table>
<thead>
<tr><th>Name</th><th>Score</th></tr>
</thead>
<tbody>
<tr><td>Alice</td><td>92</td></tr>
<tr><td>Bob</td><td>87</td></tr>
</tbody>
<tfoot>
<tr><td>Average</td><td>89.5</td></tr>
</tfoot>
</table>These grouping elements do not change the visual look by themselves, but they help CSS target specific parts and let browsers repeat headers when a long table is printed. Adding the scope attribute to <th> (scope="col" or scope="row") further clarifies which cells each header describes, which is a huge help for screen reader users.
📝 Section Recap: Tables are for data, not layout. Use
<tr>for rows,<th>for headers,<td>for data, and group rows with<thead>,<tbody>, and<tfoot>.
Getting User Input: Forms#
Forms let users send data back to the server — think login screens, search boxes, checkout pages. Every form starts with a <form> element, and two key attributes tell it where and how to send the data:
action— the URL that will handle the data (often a server script).method— the HTTP method, almost always"GET"(data visible in the URL) or"POST"(data hidden in the request body).
<form action="/submit" method="POST">
<!-- form controls go here -->
</form>Inside a form, you put interactive controls. The main one is the <input> element. Its type attribute decides what kind of input it is:
type="text"— a single-line text fieldtype="email"— a text field that validates email formattype="password"— masked texttype="number"— numeric input with up/down arrowstype="checkbox"andtype="radio"— selectable optionstype="submit"— a button that sends the form
Each input should be paired with a <label> element to give it a name and improve accessibility. Connecting a label to its input (via for matching the input’s id) makes the form easier to use — clicking the label focuses the field.
<form action="/subscribe" method="POST">
<label for="email">Email address:</label>
<input type="email" id="email" name="user_email" placeholder="you@example.com" required>
<button type="submit">Subscribe</button>
</form>Notice the name attribute on the input. This is the key that will be sent to the server along with the user’s value. required makes the field required before the form can be sent. Other useful controls include <textarea> for multiline text, <select> with <option> for dropdown menus, and <button> elements.
Forms are the starting point for interactive web apps; learning them well is important.
📝 Section Recap: Forms gather user input; always set
actionandmethod, use<label>with every control, and pick the righttypeof<input>to collect the right data.
Meaningful Structure: Semantic Elements#
Early HTML pages were often a mess of <div> tags with vague class names. Modern HTML5 introduced a set of semantic elements that clearly describe the role of each part of the page. This makes code easier to read, helps search engines find the real content, and gives assistive technology a much clearer map of the page.
Key semantic structural elements include:
<header>— the introductory area of a page or a section, usually containing a logo, title, and navigation.<nav>— a block of navigation links (the main menu).<main>— the core content unique to the page; there should be only one per page.<section>— a thematic grouping of content, typically with a heading.<article>— a self-contained composition that could stand on its own (a blog post, a news story, a comment).<aside>— content tangentially related to the main content, like a sidebar or a pull quote.<footer>— the closing area, often with copyright info, contact details, and secondary links.
A typical page layout might be:
<body>
<header>
<h1>My Blog</h1>
<nav>
<a href="/">Home</a> | <a href="/about">About</a>
</nav>
</header>
<main>
<article>
<h2>Post Title</h2>
<p>Article body...</p>
</article>
<aside>
<p>Related links...</p>
</aside>
</main>
<footer>
<p>© 2025 My Blog</p>
</footer>
</body>Even though these elements behave like <div> blocks by default, their names carry real meaning. A search engine can give more weight to content inside <article>, and a screen reader can announce a <nav> section and let a user skip to it instantly. This is the heart of writing semantic HTML: choosing tags that describe the purpose of the content, not just its appearance.
📝 Section Recap: Semantic elements like
<header>,<nav>,<main>,<section>,<article>, and<footer>give structure and meaning, making pages more accessible and understandable by both humans and machines.
Fine-Tuning: id, class, Iframes, and Special Characters#
id and class attributes#
In your HTML, you’ll often want to mark specific elements for styling or scripting. Two global attributes do this:
id— a unique identifier for an element. You can use it to link to a specific part of the page (via#id-nameinhref) or to target an element precisely in CSS and JavaScript. Anidmust be unique within the page: no two elements can share the sameid.class— a category name that can be applied to many elements. Use classes to group similar things (like all “button” styles, or all “highlighted” notes). An element can have multiple classes, separated by spaces.
<p id="intro" class="highlight important">This is the introduction paragraph.</p>These attributes don’t change the meaning of the HTML, but they are important hooks for CSS and JavaScript.
Embedding another page with iframe#
An <iframe> (inline frame) embeds another entire HTML document inside your page — for example, a YouTube video, a map, or an advertisement. Use it responsibly, as it can slow down your page and introduce security risks.
<iframe src="https://www.youtube.com/embed/videoID"
width="560" height="315"
title="A descriptive video title"
allowfullscreen></iframe>Always include a title attribute for accessibility. To restrict what the embedded page can do (e.g., prevent it from running scripts or sending forms), use the sandbox attribute with appropriate values.
HTML escape characters#
Some symbols have special meaning in HTML: <, >, &, ", and '. If you need to display them as text (not as part of a tag), use HTML escape characters (also called entities). They start with & and end with ;.
| Character | Escape sequence | Meaning |
|---|---|---|
< |
< |
less-than sign |
> |
> |
greater-than sign |
& |
& |
ampersand |
" |
" |
double quote |
' |
' |
apostrophe (single quote) |
© |
© |
copyright symbol |
| non-breaking space | |
space that will not wrap |
For example, to show “5 < 10” in a paragraph, you write 5 < 10. Otherwise, the < might be mistaken for a tag opener. Using entities keeps your code valid and predictable.
📝 Section Recap:
idgives an element a unique name,classgroups similar elements,<iframe>embeds external pages, and HTML entities let you safely display reserved symbols like<and&.
Summary#
You’ve just built a full picture of an HTML document. It starts with the important <!DOCTYPE html>, goes through the hidden <head> that gives metadata to browsers and search engines, and ends in the rich, structured <body> where all the visible content lives. We saw how picking the right semantic elements makes a page readable by both people and software. We also saw how attributes like id, class, and correct nesting turn a simple file into a strong, easy-to-update base for everything that follows. Remember: HTML is not about memorizing every tag, but about understanding the meaning each tag carries and using that meaning to describe your content clearly. With this chapter under your belt, you can write a valid, well-structured HTML document from scratch — the first skill of any web developer.
| Key idea | What it means (plain English) | Why it matters |
|---|---|---|
| DOCTYPE declaration | The very first line in an HTML file (<!DOCTYPE html>), telling the browser to use modern display rules. |
Prevents the browser from switching to “quirks mode,” which makes pages look inconsistent. |
<head> vs <body> |
<head> holds hidden information (title, charset); <body> holds everything the user sees. |
Separating settings from content keeps the document organized and helps browsers load pages efficiently. |
| Semantic HTML | Using tags like <header>, <article>, <nav> that describe the purpose of content, not just its appearance. |
Improves accessibility, search engine ranking, and code readability — humans and machines understand your page better. |
Headings <h1>–<h6> |
Levels that create a document outline, with <h1> as the main title and others as subheadings. |
Gives screen reader users a navigable outline and tells search engines the page’s structure. |
Hyperlinks <a> |
Elements that turn text or images into clickable links using href. |
The fundamental “web” in the World Wide Web; links connect pages and resources together. |
Image alt text |
A description for an image inside <img alt="...">, shown when the image cannot be loaded or read aloud by screen readers. |
Makes visual content accessible to blind users and provides context if the image breaks. |
Tables (<table>, <th>, <td>) |
A grid of rows and cells for presenting data, with headers to explain what each column/row means. | Gives structure to data so it is easy to scan; semantic table markup helps assistive technology read it correctly. |
Forms (<form>, <input>) |
Interactive controls that collect user input and send it to a server using action and method. |
The starting point for login, search, checkout, and any user interaction beyond reading. |
id and class |
id gives a unique name to one element; class is a label you can reuse on many elements. |
Enables precise styling with CSS and targeting with JavaScript; id also allows in-page linking. |
HTML entities (<, &) |
Special codes that represent reserved characters like <, >, and & so they appear as ordinary text. |
Keeps your HTML valid and ensures special symbols display correctly without breaking the markup. |