HTML Comments

In this tutorial, you will learn about HTML comments with the help of examples.

The HTML comments are used to add extra information to a web page. For example,

<!-- this is a HTML comment. -->

The HTML Comment tag (<!-- comment here -->) is used to insert text to the webpage which is not rendered by the browser.

The HTML comments can be seen while reading the code but get ignored by the browser during the rendering of the page. For example,

  <!-- a random comment.  -->
  <p>HTML is fun to learn.</p>

Browser Output

An HTML comment written between <!-- and -->


<!-- a random comment -->

is a comment.

In HTML, comments have a distinct syntax to differentiate them from other elements. The HTML comments begin with <!-- and end with -->.

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

Multiple HTML paragraphs with one inside a comment

Keyboard Shortcut for HTML Comments

Most code editors 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.