Comments and Whitespace
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.
The shortcut
When predicting what text will look like, squeeze every whitespace run to one space and delete every comment. What remains is what the visitor sees.
Start with the source
<p>Price: <!-- update monthly --> ₹499</p>
The trap is fighting the collapse with a pile of entities or empty paragraphs. That is layout, and layout belongs in CSS.
Collapsing also happens at the edges of an element: spaces just inside the opening or closing tag of a paragraph are not displayed. So you can freely put a paragraph's text on its own indented line in your source; the visitor never sees that indentation.
Drills
Answer fast — trust the rule.
How is <p>one two</p> displayed?
Which is a correctly written HTML comment?
Can visitors see what is written in your HTML comments?
You are marking up a postal address where each part must sit on its own line. What fits best?
Remember
- Runs of whitespace collapse to one space; comments
<!-- -->are never displayed. - Shortcut: delete comments, squeeze whitespace, and you have what the visitor sees.
- Trap: faking layout with spaces or
, and leaving secrets in comments.
