HTML Comments

HTML comments are used to insert notes or explanations within your HTML code. These comments are not displayed in the browser but can be very helpful for documenting your code, making it easier to understand and maintain.

Syntax

HTML comments start with <!-- and end with -->. Anything between these tags will be treated as a comment and will not be rendered by the browser.

<!-- This is a single-line comment -->
<p>This is a paragraph.</p>

Examples

1. Single-Line Comment

<!DOCTYPE html>
<html>
<head>
    <title>Single-Line Comment Example</title>
</head>
<body>
    <!-- This is a single-line comment -->
    <p>This is a paragraph.</p>
</body>
</html>

In this example, the comment <!-- This is a single-line comment --> is added above the paragraph element. It will not be displayed on the web page.

2. Multi-Line Comment

<!DOCTYPE html>
<html>
<head>
    <title>Multi-Line Comment Example</title>
</head>
<body>
    <!-- 
    This is a multi-line comment.
    It can span multiple lines.
    -->
    <p>This is a paragraph.</p>
</body>
</html>

In this example, the comment spans multiple lines, making it useful for longer explanations or notes.

3. Hiding Code

Comments can also be used to temporarily hide parts of your HTML code. This can be useful for debugging or testing purposes.

<!DOCTYPE html>
<html>
<head>
    <title>Hiding Code Example</title>
</head>
<body>
    <p>This paragraph is visible.</p>
    <!-- <p>This paragraph is hidden and will not be displayed.</p> -->
</body>
</html>

In this example, the second paragraph is commented out and will not be displayed on the web page.

4. Using Comments for Documentation

Comments are often used to document sections of code, making it easier for others (or yourself) to understand what the code does.

<!DOCTYPE html>
<html>
<head>
    <title>Documentation Example</title>
</head>
<body>
    <!-- Main content section -->
    <h1>Welcome to My Website</h1>
    <p>This is the main content of the page.</p>
    
    <!-- Footer section -->
    <footer>
        <p>Contact us at info@example.com</p>
    </footer>
</body>
</html>

In this example, comments are used to label the main content and footer sections of the HTML document.

Conclusion

HTML comments are a valuable tool for adding notes, explanations, and documentation to your code. They help improve code readability and maintainability without affecting the rendered output. Use comments wisely to make your HTML code more understandable and easier to work with.

Share this Tutorials

HTML Comments

Or copy link

CONTENTS
Scroll to Top