HTML – Comments

By Published 2 min read

HTML comments are an essential part of web development. They allow developers to include notes or explanations within the HTML code that are not visible to website visitors. Here’s how HTML comments work and why they are valuable:

  1. Syntax: HTML comments are enclosed within <!-- and -->. Anything between these delimiters is considered a comment and is not rendered in the browser.
  2. Purpose: Comments serve multiple purposes in web development:
  • Documentation: Developers can add comments to explain how certain parts of the code work, making it easier for themselves and others to understand and maintain the code in the future.
  • Debugging: Comments can help identify and locate issues in the code by providing context or clues about specific sections.
  • Temporary Removal: You can temporarily “comment out” code by enclosing it in comments. This prevents it from being executed but retains it for future reference.
  1. Example:
   <!-- This is an HTML comment. It won't be visible on the webpage. -->

   <p>This is visible text.</p>

   <!-- You can use comments to explain complex code structures or leave notes for yourself or other developers. -->Code language: HTML, XML (xml)
  1. Nesting: HTML comments can be nested within each other, but you must ensure that they are properly opened and closed to avoid syntax errors.
  2. Best Practices:
  • Be descriptive: Write comments that provide meaningful explanations, especially for complex or non-standard code.
  • Keep comments concise: Avoid overly long comments that make the code harder to read.
  • Remove unnecessary comments: Periodically review your code and remove comments that are no longer relevant or informative.

Here’s an example of how comments might be used in HTML:

<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
    <!-- This is a meta description for SEO -->
    <meta name="description" content="A sample website for illustration purposes.">
</head>
<body>
    <!-- Header Section -->
    <header>
        <h1>Welcome to My Website</h1>
    </header>

    <!-- Main Content -->
    <section>
        <h2>About Us</h2>
        <!-- TODO: Add more content here -->
    </section>

    <!-- Footer Section -->
    <footer>
        <p>&copy; 2023 My Website</p>
    </footer>
</body>
</html>
Code language: HTML, XML (xml)

In this example, comments provide explanations and structure to the HTML code, making it more understandable and maintainable for developers.

HTML comments are a valuable tool for web developers, helping to improve code readability, collaboration, and maintenance. They are a non-visible but essential part of creating well-documented and maintainable web pages.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume