FullStack Course LogoFullStack Course
Module: HTML
HTML·002·11 MIN READ

002: HTML Document Structure

TOPICS COVERED: HTML Document Structure

Learning outcomes

By the end of this lesson, you can create a conforming HTML document; explain doctype, html, head, body, metadata, elements, tags, and attributes; nest elements correctly; and use indentation and comments without confusing presentation with structure.

Prerequisites and retrieval

Create a portfolio folder and open it in a text editor. Before moving on, recall lesson 001: which resource normally supplies a page's structure, and which software parses that resource? Also explain why an HTTP 200 response tells you that a response was returned, but does not prove that its HTML is well formed.

Terminology

  • Markup: Text annotations that define document structure and meaning, independent of appearance. — Source: WHATWG: HTML Introduction
  • Element: The basic building block of HTML: a start tag, content, and an end tag (or a void element). — Source: WHATWG: Elements
  • Tag: Markup syntax delimiting where an element starts and ends in source text. — Source: WHATWG: The HTML syntax
  • Attribute: A name/value pair inside a start tag that configures or annotates its element. — Source: MDN: Glossary — Attribute
  • Nesting: Placing elements inside other elements so parsed markup forms a tree. — Source: MDN: Basic HTML syntax
  • Void element: An element that can never have children or an end tag, such as meta, img, or input. — Source: WHATWG: Void elements
  • Metadata: Information about the document itself — encoding, viewport, title — carried in the head element. — Source: WHATWG: Document metadata
  • DOM: The browser’s live tree representation of a document that scripts can read and modify. — Source: MDN: Document Object Model
  • Conformance checker: A tool that reports violations of a specification’s authoring requirements. — Source: Nu HTML Checker
  • HTML: "HyperText Markup Language — the markup language that describes the structure and semantics of web documents." — Source: WHATWG HTML Living Standard: Introduction
  • Semantics: "The meaning conveyed by an element, independent of presentation." — Source: MDN: Semantics
  • Character reference: "A code such as < representing a character that would otherwise be parsed as markup." — Source: WHATWG: Character references
  • Conforming document: "A document that conforms to the requirements of this specification." — Source: WHATWG: Conformance requirements

Mental model: source becomes a tree

HTML is not a list of drawing commands. It declares a document and the relationships among its parts. The browser parses the source text into a tree: html contains head and body, body contains the content presented to the user, and elements can contain text plus other elements that are permitted in that context.

text
Document
├─ doctype
└─ html (lang="en")
   ├─ head
   │  ├─ meta charset
   │  ├─ meta viewport
   │  └─ title
   └─ body
      └─ h1

Browsers recover from many authoring errors, partly so older pages remain usable. That recovery is not the same as validation. In <p>Welcome <strong>friend</p></strong>, the closing tags do not mirror the opening order. The browser follows defined error-recovery rules and can produce a DOM that differs from the tree the author intended. Write deliberate, conforming nesting instead of depending on the parser to repair it.

The document skeleton

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Home | Asha Rao</title>
  </head>
  <body>
    <h1>Asha Rao</h1>
    <p>Building accessible, semantic websites.</p>
  </body>
</html>

<!doctype html> selects standards mode. It is the required preamble for a normal HTML document, not an HTML element and not a version declaration that means “HTML5.” The document element is <html>. Its lang attribute identifies the page's human language, which supports pronunciation, translation, and other processing.

<head> contains metadata about the document. Put <meta charset="utf-8"> early; UTF-8 is the usual authoring choice. The viewport declaration asks mobile browsers to use the device width with an initial scale of 1. Do not disable user zoom with user-scalable=no or a restrictive maximum scale.

<title> supplies the document title shown in browser tabs, history, bookmarks, and often search results. Make it meaningful and distinguishable: About | Asha Rao gives more useful context than Page.

<body> contains the document content presented to the user. Metadata and visible headings serve different jobs: <title> does not replace <h1>, and <h1> does not replace <title>.

Tags, content, and attributes

Take <p class="intro">Hello</p> apart. <p class="intro"> is the start tag, class="intro" is an attribute, Hello is text content, and </p> is the end tag. Together, those pieces represent one paragraph element. Quote attribute values consistently. Attribute order normally has no semantic effect, but duplicate attributes are authoring errors.

Void elements have no end tags. Write <meta charset="utf-8">, not <meta charset="utf-8"></meta>. HTML syntax permits a trailing slash in <meta ... />, but the slash is unnecessary and does not “close” the element. This course uses straightforward HTML syntax rather than XHTML-style slashes.

Boolean attributes use presence as their value. Later, required will mean required whether it is written as required, required="", or required="required"; required="false" still means true. Omit the attribute when the intended value is false.

Indentation and comments

Browsers mostly ignore indentation between elements, but people reading the source do not. Indent children by two spaces and align paired tags. The visible shape then reflects the document tree and makes missing end tags easier to spot.

html
<!-- Explain why a non-obvious structural choice exists. -->

Comments are delivered to users and can be seen in page source and developer tools. Never put passwords, tokens, private notes, or removed confidential material in them. Comments cannot be nested. Use clear markup instead of comments that merely repeat what the markup already says.

HTML syntax conventions, case, and whitespace

In HTML documents, element and attribute names are ASCII case-insensitive, so a browser recognizes markup such as <P> or <TITLE>. That is a parsing rule, not a good authoring convention. Use lowercase element and attribute names consistently:

html
<p class="summary">Readable, conventional HTML.</p>

Consistency makes source easier to scan, diffs easier to review, and searches more predictable. It also prevents confusion when you move between HTML and case-sensitive languages or formats.

HTML normally collapses sequences of ordinary whitespace in text. These two paragraphs render with equivalent spacing between the words:

html
<p>Hello     world</p>
<p>Hello world</p>

Use markup for structure and CSS for visual spacing. Do not try to align page content by inserting runs of spaces. When whitespace itself is part of the content, use an element such as pre; lesson 003 covers that case.

Global attributes: id, class, lang, title, and data-*

Some attributes apply to most HTML elements. These are called global attributes.

html
<article
  id="project-weather"
  class="project featured"
  lang="en"
  data-project-id="8472">
  ...
</article>
  • id identifies one element within the document. Keep IDs unique.
  • class assigns one or more reusable classification tokens. Many elements may share the same class.
  • lang declares the language of an element and its descendants unless another declaration overrides it. It helps with pronunciation, translation, spell checking, and search processing.
  • title can provide advisory information, but do not put essential instructions there: it is not reliably available to keyboard, touch, or assistive-technology users.
  • data-* stores application-specific data on an element, such as data-project-id="8472". Use it when scripts need metadata for which HTML has no native attribute.

Do not use data-* as a substitute for real semantics. If HTML already provides a suitable element or attribute, use that native feature instead.

class and id are not styling instructions by themselves. CSS can select them, links can target an id, and JavaScript can use both, but simply adding either attribute does not automatically change the element's appearance.

Boolean attributes and quoted values

For a boolean attribute, presence means true and absence means false:

html
<input type="checkbox" checked>
<input type="text" required>

checked="false" still means checked because the attribute is present. Remove the attribute to express false.

HTML permits some unquoted attribute values, but consistently quoting normal values is the safer authoring habit. Quotes prevent spaces and special characters from accidentally changing how the source is parsed:

html
<p class="project summary">...</p>

That small convention becomes increasingly useful as documents grow.

Guided example: build and explain index.html

  1. In portfolio, create index.html.
  2. Type the skeleton rather than using an editor shortcut. Writing it out builds recognition.
  3. Set lang="en" because the page content is English. Use a more specific valid language tag when the page needs one.
  4. Put charset first in head, followed by viewport and title.
  5. Add visible content to body:
html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Home | Asha Rao</title>
  </head>
  <body>
    <h1>Asha Rao</h1>
    <p>I am learning to build useful, accessible websites.</p>
  </body>
</html>
  1. Save the file and open it in a browser. The address begins with file: because no web server is involved. Notice that the tab uses title while the page displays h1.
  2. Open developer tools and inspect the Elements/Inspector tree. Compare that parsed tree with the source.
  3. Explain each major line by its purpose, not just by reading its characters: say “This declares the page language,” rather than “This says html lang equals en.”

The browser supplies default presentation, but appearance is not the reason to choose an element. CSS can change that appearance later; the element's meaning should remain appropriate.

Intermediate example: inspect browser recovery

Temporarily create broken.html:

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Broken nesting experiment</title>
  </head>
  <body>
    <p>My <strong>first portfolio paragraph.</p></strong>
  </body>
</html>

The page may look acceptable. Inspect its DOM and submit the source to the Nu HTML Checker. The checker reports the structural mistake even when rendering makes the problem hard to see. Correct the order:

html
<p>My <strong>first portfolio paragraph</strong>.</p>

Trace the markup like a stack: opening <p> pushes p, and opening <strong> pushes strong; therefore <strong> must close before <p>. Indentation gives you the same visual clue.

Advanced optional extension: source, DOM, and conformance

HTML allows some tags to be omitted under exact rules, but beginners should normally write the clear skeleton and ordinary end tags. Developer tools show the parsed DOM, which is not always an exact copy of the source. The browser may insert implied elements or repair invalid nesting. “View Source” shows the delivered source; “Inspect” shows the resulting live tree.

Try omitting <html>, <head>, and <body>. The DOM still contains those elements because the parser implies them. Restore the explicit tags: they make the document easier to review and maintain. Do not infer that every closing tag is optional; omission rules vary by element and context.

Common mistakes and debugging

  • Missing doctype: can trigger quirks mode and inconsistent legacy layout behavior.
  • Putting visible content in head: move document content to body.
  • Using title as a tooltip myth: the title element names the document; the global title attribute is different and is not a dependable replacement for visible instructions.
  • Crossed nesting: close the most recently opened inner element first.
  • Closing void elements: img, meta, and input have no end tag.
  • Duplicate IDs or attributes: validators catch many such authoring errors.
  • Assuming rendering proves validity: inspect the source and parsed tree, then use a conformance checker.
  • Using comments for secrets: comments are public once delivered.

Accessibility, security, and performance

Set the correct lang; WCAG 2.2 requires a programmatically determinable page language. Give every page a descriptive title, and keep zoom available. Semantic structure gives assistive technology useful information, but passing syntax validation is not the same as completing an accessibility audit.

HTML comments and metadata are not private. Do not leak internal paths, personal details, or credentials through them. UTF-8 avoids many encoding ambiguities, while servers must also send the correct Content-Type and charset. A concise document head and valid tree are easy to process, but micro-optimizing indentation is pointless under normal compression. Optimize images and scripts later without sacrificing semantic clarity.

Tiered exercises

Level 1: complete the skeleton

Create a valid English document titled About | Your Name, with one heading and paragraph. Explain the doctype, language, charset, viewport, title, and body.

Level 2: repair

Correct this source and list each reason:

html
<html>
<head><title>Page</title></head>
<body><h1>About <em>me</h1></em><meta charset="utf-8"></body>
</html>

Level 3: investigate

Compare View Source and the DOM for malformed nesting. Run the corrected document through the Nu checker and explain why “no errors” is useful but not a complete quality guarantee.

Level 1:

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>About | Sam Lee</title>
  </head>
  <body>
    <h1>About Sam Lee</h1>
    <p>I am learning web development and documenting my progress.</p>
  </body>
</html>

The doctype selects standards mode; lang identifies English; charset selects UTF-8; viewport supports mobile sizing without blocking zoom; title identifies the document; body contains presented content.

Level 2:

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>About | Your Name</title>
  </head>
  <body>
    <h1>About <em>me</em></h1>
  </body>
</html>

This adds the doctype and language, puts early metadata in head, adds viewport metadata, gives the document a descriptive title, and closes em before its parent heading.

Level 3: View Source retains the malformed order; the inspector may show a repaired tree. Zero checker errors means that checker version detected no conformance errors. It does not prove good writing, accurate alt text, usable keyboard behavior, security, or full accessibility.

Recap and exit questions

HTML source declares a meaningful tree. A standard document has a doctype, an html root with a language, metadata in head, and content in body. Browsers repair errors, while validators help authors find them.

  1. What is the difference between a tag and an element?
  2. Why are <title> and <h1> both needed?
  3. What does the doctype do?
  4. Why can the DOM differ from source?
  5. Why is required="false" still true for a boolean attribute?

Try it with your own example

You have seen Asha's skeleton; now build the same shape for a different purpose. That forces the pattern to become reusable instead of remaining “the code I copied for Asha.”

Create a folder called rinas-kitchen next to your portfolio folder. Inside it, write index.html for the bakery from lesson 001, using memory rather than copying:

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Home | Rina's Kitchen</title>
  </head>
  <body>
    <h1>Rina's Kitchen</h1>
    <p>Fresh sourdough and pastries, baked every morning in the old town.</p>
  </body>
</html>

Ask yourself, out loud if possible, why lang="en" belongs here even though Rina might later add a French menu page at menu-fr.html with lang="fr" of its own. Then consider why <title>Rina's Kitchen</title> without “Home |” is a weaker choice once five pages are open in five browser tabs. If you can answer both without looking back at the lesson, the skeleton has become yours rather than something memorized for one project.

Further reading: MDN — What's in the head? walks through additional head metadata (favicons, author info) you will meet again in the bonus SEO lesson (016) later in this course.

Official references

Reader page: /html/lesson/002/html-document-structure