HTML course menu
HTML Comments: Syntax, Uses and What Not to Put in Them
Learn how to write HTML comments with <!-- and -->, use them to explain code and temporarily disable markup, the keyboard shortcut in editors, and why comments must never contain secrets.
A comment is a note in your HTML that the browser does not display. Comments explain your code to other people (and to you, months later) and let you switch off part of a page while testing.
Syntax#
A comment starts with <!-- and ends with -->. It can span several lines:
<!-- Main heading of the page -->
<h1>Welcome</h1>
<!--
The newsletter section is hidden until
the sign-up form is ready.
-->
<p>Thanks for visiting.</p>Only the heading and the paragraph appear in the result. The comments are still in the file, and anyone can read them with View Page Source or the developer tools.
Commenting out markup#
To hide part of a page temporarily without deleting it, wrap it in a comment:
<p>Visible paragraph.</p>
<!-- <p>This paragraph is switched off.</p> -->
<p>Another visible paragraph.</p>Good uses for comments#
- Marking where large sections start and end in a long file.
- Explaining why something unusual is done.
- Leaving a temporary note while you work, such as
<!-- TODO: add the real phone number -->.
Avoid comments that repeat what the code already says, such as <!-- paragraph --> above a <p>.
Rules and limits#
- Comments cannot be nested. The first
-->ends the comment, so anything after it is shown as normal content:
<!-- outer <!-- inner --> this text is NOT inside a comment -->- Comments work inside
<head>and<body>, but not inside a tag. You cannot put a comment between attributes.
Practice#
Practice exercise
Write three paragraphs, "One", "Two" and "Three", with a comment above them saying Numbers section. Then comment out the second paragraph so only "One" and "Three" are shown.
Show solution
<!-- Numbers section -->
<p>One</p>
<!-- <p>Two</p> -->
<p>Three</p>Key takeaway#
Finished this lesson?