20. HTML Comments
What you will learn
- How to write a comment in HTML
- What comments are good for
- How to hide code temporarily
- What comments should never contain
What is a comment?
A comment is a note in your code that the browser ignores. Comments are for people who read the code, including you in six months’ time.
Syntax
<!-- This is a comment -->
A first example
Example
<!-- Main page heading -->
<h1>Welcome</h1>
<p>This paragraph is visible.</p>
<!-- <p>This paragraph is hidden.</p> -->
Output
Welcome
This paragraph is visible.
The comment text and the commented-out paragraph do not appear on the page.
Multi-line comments
A comment can run over several lines. Everything between <!-- and --> is ignored.
Example
<!--
Section: pricing table
To do: add a yearly plan
-->
What comments are useful for
- Explaining why something was written in a certain way.
- Labelling sections of a long page, for example
<!-- Footer -->. - Leaving reminders to yourself or your team.
- Testing: temporarily switching off a piece of code without deleting it.
Shortcut in your editor
In Visual Studio Code, select the lines and press Ctrl+/. The editor adds or removes comment markers for you.
Comments are not private. Anyone can see them by choosing “View page source” in their browser. Never put passwords, secret links, personal data, or private notes in an HTML comment.
Good habits
- Explain the why, not the obvious. A comment saying “this is a paragraph” above a
<p>adds nothing. - Keep comments short and up to date. A wrong comment is worse than none.
- Remove old commented-out code before publishing, so pages stay small and tidy.
Common mistakes
- Forgetting the closing
-->. Everything after the comment then disappears. - Putting a comment inside a tag, such as
<p <!-- note --> >. Comments go between elements, not inside tags. - Nesting comments. A comment ends at the first
-->, so commenting out code that already contains a comment breaks. - Leaving private information in comments.
Exercise
Add a comment that says Navigation starts here, followed by a paragraph. Then hide a second paragraph using a comment.
Show solution
<!-- Navigation starts here -->
<p>Visible text</p>
<!-- <p>Hidden text</p> -->
Knowledge check
1. How does an HTML comment begin and end?
It begins with <!-- and ends with -->.
2. Can visitors see your comments?
Yes, in the page source, even though they do not appear on the page.
3. What shortcut comments out a line in VS Code?
Ctrl+/
Summary
- Comments use
<!-- ... -->and are ignored by the browser. - Use them to explain, label, and temporarily hide code.
- Never store secrets in comments.