HTML Comment Tag – How to Add Comments in HTML with Examples

What is the HTML Comment Tag?

The HTML Comment Tag (<!-- -->) allows you to add hidden notes in your HTML code that do not appear on the webpage. Comments are useful for:
✔ Explaining code for future reference.
✔ Temporarily disabling parts of the code.
✔ Helping teams collaborate more efficiently.

Syntax:

<!-- This is a comment -->

Basic Example of HTML Comments

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML Comment Example</title>
</head>
<body>
    <h1>Welcome to My Website</h1>

    <!-- This paragraph is temporarily hidden -->
    <!-- <p>This is a hidden message.</p> -->

    <p>This paragraph is visible to users.</p>
</body>
</html>

Output:
Welcome to My Website
This paragraph is visible to users.

🚀 The comment inside <!-- --> is ignored by the browser.

Multi-line Comments in HTML

You can write multi-line comments using the same <!-- --> syntax.

 
<!-- 
This is a multi-line comment.
It will not be displayed in the browser.
It is useful for documenting sections of code.
-->

Best Use Case:

<!-- Header Section -->
<header>
    <h1>My Website</h1>
</header>

Using Comments for Debugging

If you want to disable a part of your HTML code without deleting it, comment it out.

<!-- <button>Click Me</button> -->

🚀 This prevents the button from appearing on the page without removing the code.

Comments Inside HTML Attributes

You cannot use HTML comments inside an HTML tag’s attribute value.

Incorrect Usage:

<p title="<!-- Hidden title -->">Hello</p>

Correct Usage:

<!-- Title is set inside the p tag -->
<p title="Hello Message">Hello</p>

HTML Comments vs. JavaScript Comments

HTML comments (<!-- -->) are different from JavaScript comments (// or /* */).

JavaScript Comment Example:

<script>
    // This is a single-line comment in JavaScript
    
    /*
    This is a 
    multi-line comment in JavaScript
    */
</script>

Best Practices for Using HTML Comments

Use comments to explain complex code sections.
Avoid excessive comments. Too many comments make the code cluttered.
Do not leave sensitive information in comments.
Use comments to separate sections for better readability.