HTML comments are used to insert notes to a web page. For example,
<!-- heading 2 -->
<h2>Comments in HTML</h2>
Here, <!-- heading 2 -->
is a comment. In HTML, comments start with <!--
and ends with -->
HTML comments are not displayed by browsers. They are used to add notes for documentation purposes within code. For example,
<!-- an HTML div -->
<div>
<p>HTML is fun to learn.</p>
</div>
Browser Output
Here,
<!-- an HTML div -->
is a comment. Hence, it is not displayed in the browser output.
Why use HTML Comments?
Comments are mainly used to make our code more readable. They are completely hidden from the webpage and only show up in the code.
Commenting on your code is a good practice as it helps us to express what the code is doing. It can act as an anchor for you if you want to change your code in the future.
In a collaborative environment, code comments are helpful for other developers as well.
Note: Even though browsers don't display comments, it's still possible to view comments using the browser's View Source feature. That's why we must not add sensitive information inside comments.
Single-Line and Multi-line Comments
In HTML, we use the same syntax to create single-line and multi-line comments.
Single Line Comment
<!-- Write a heading -->
<h1>Important Heading</h1>
Multi-line Comments
<!-- Multiple Line comments
can include line breaks
and also extra spaces -->
<p>this will display in the webpage</p>
HTML Tags Inside Comments
If we put HTML elements inside comments, they will be ignored. For example,
<p>this will be displayed</p>
<!-- <p>this will not be displayed</p> -->
<p>this will also be displayed</p>
Browser Output
Keyboard Shortcut for HTML Comments
Most code editors (including Programiz's Online HTML Editor) have a keyboard shortcut for commenting code.
In general, most code editors use Ctrl + /
(on Windows or Linux) and Cmd + /
(on Mac) for creating comments.
We encourage you to remember these shortcuts as comments are used frequently to add extra information as well as to temporarily remove certain code.