Skip to the workspace
Pebellslearn by building
HTML Syntax  ›  Lesson

Comments and Whitespace

Whitespaces 12 minAn HTML comment records source text outside the document's visible content. Whitespace becomes text nodes, whose visual collapsing or preservation depends on the element and CSS white-space rules.

html / Comments and Whitespace

Explore each scene at your own pace.

01 · The rule

The rule

Comments and Whitespace

An HTML comment records source text outside the document's visible content. Whitespace becomes text nodes, whose visual collapsing or preservation depends on the element and CSS white-space rules.

Inspect comments in the source and compare normal whitespace with preserved formatting.

You press Enter five times to leave a big gap between two paragraphs, reload the page, and the gap is gone. Browsers treat spaces very differently from a word processor, and knowing the rule saves a lot of confusion. The same lesson covers comments: text in your file that the browser deliberately never shows.

The rule

Many spaces become one; comments are never shown.

Whitespace collapses. In ordinary text, any run of spaces, tabs and line breaks is displayed as a single space. These two paragraphs look identical in the browser:

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

That is actually useful: you can indent and wrap your HTML to keep it readable without changing what visitors see. When line breaks are part of the content, such as a poem or a postal address, use <br>. When every space matters, such as a code listing, use <pre>, which keeps whitespace exactly as typed. Both appear in the next sections. When you only want visual space, use CSS margins, not blank lines.

Comments are hidden. A comment starts with <!-- and ends with -->:

<!-- Main navigation: update when the blog launches -->
<nav>...</nav>

Use comments to explain why something is there, or to temporarily switch off a block while testing. Two cautions: comments cannot be nested, and they are hidden only from the display. Anyone can read them with "View source", so never put passwords, private notes or secrets in them.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.