Comments, whitespace & HTML entities
4 min lesson
- An HTML comment is a note for humans that the browser ignores, written as <!-- note -->.
- Whitespace in HTML source is collapsed: many spaces and newlines become one space on screen.
- An HTML entity is a short code that shows a special character, like < for < or & for &.
- Entities matter because characters like < and > have meaning in HTML and would otherwise be read as tags.
- This builds on Attributes & global attributes: you now know the tag parts, and here you learn what goes between them.
- The example shows a comment, several spaces that collapse, and entities for <, > and &.
- Next, Semantic HTML shows how to choose tags that carry meaning.
- Use comments to explain your HTML, not to hide code.
- Do not rely on many spaces for layout; the browser collapses them.
- Use < and > to show angle brackets as text.
- Always escape & as & when it is not part of an entity.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Entities</title>
</head>
<body>
<!-- This comment is for humans; the browser ignores it -->
<p>Here are many spaces: a b</p>
<!-- The browser collapses the extra spaces into one -->
<p>To show a tag, write <p> instead of <p>.</p>
<!-- & shows a literal ampersand -->
<p>Tom & Jerry</p>
</body>
</html>What happens: A page showing "Here are many spaces: a b" (single space), "To show a tag, write <p> instead of ." (the <p> is shown as text), and "Tom & Jerry".
Breaking it down
Comment
<!-- note -->A note for people reading the source. The browser does not show it or use it in layout.
Collapsed whitespace
a bHTML treats any run of spaces, tabs and newlines as one space. To control spacing, use CSS later.
Entity <
<Shows a less-than sign as text. Without it, the browser would think a tag is starting.
Entity &
&Shows a literal ampersand. Without it, the browser may think an entity is starting.
Common HTML entities
| Entity | Shows |
|---|---|
| < | < |
| > | > |
| & | & |
| " | " |
| | A non-breaking space |
A helpful analogy
Entities are like escape codes on a keyboard: you press a special key to type a character you cannot type directly. In HTML, < is the special key that means 'show a less-than sign as text.'
Nesting rules
- 1.Keep comments short and out of the middle of a tag.
- 2.Never nest one comment inside another; the first --> closes it.
Common mistakes
Typing a raw < inside text
Avoid
<p>Use <p> for paragraphs</p>Use instead
<p>Use <p> for paragraphs</p>The browser reads <p> as a real tag. The closing </p> then arrives early and the layout breaks.
Using many spaces to align text
Avoid
<p>A B</p>Use instead
<p>A B</p> plus CSS for spacingHTML collapses runs of spaces, so the alignment disappears. Use CSS when you need real spacing.
Quick tips
- •View source (Ctrl+U) to see comments other developers left on a page.
- •Use only when two words must stay together, for example 5 km.