HTML Comments

The HTML comments are used to indicate sections of a document or insert notes explaining the code. They help understand the code and increase its readability. The comment tag can also be used for excluding temporary code blocks instead of deleting them.

For defining HTML comments we use the <!-- ... --> tag. Browsers ignore this tag and do not show its content to the user.

Only a few browsers support the comment tag for commenting a part of an HTML code.

HTML comments can be used anywhere in the document except for the <title> tag. They do not work within the <style> tag either, as CSS uses another syntax for comments.

Valid vs Invalid Comments

A comment cannot be inserted into another comment. The double-dash sequence (“--”) may not come inside a comment if it is not a part of the closing (-->) tag. It is also important to ensure that there aren’t spaces in the start-of comment string.

Multiline Comments

HTML supports both single-line and multi-line comments. We can use multi-line comments by the beginning tag <!-- and ending tag -->.

Commenting Style Sheets

When using CSS in an HTML code, it is recommended to put the style sheet code inside appropriate HTML comments for the proper work of old browsers.

Commenting Script Code

When using JavaScript or VB Script in the HTML code, it is recommended to put the script code inside appropriate HTML comments for the proper work of old browsers.

Syntax

Comments are written between <!-- and --> symbols.

Example of an HTML comment:

<!DOCTYPE html>
<html>
  <head>
    <title>The title of the document.</title>
  </head>
  <body>
    <h1>The main heading</h1>
    <!--  <p>We want to hide this part of the code temporary. </p> -->
    <a href="https://www.w3docs.com">Homepage</a>  
    <!--  <p>This is a link to the homepage</p> -->
  </body>
</html>

Result




Do you find this helpful?

Related articles