Skip to content

Using HTML Comments: Key Techniques for Improving Code Readability ​

What are HTML Comments? ​

Comments are like "sticky notes" in your code. They exist in HTML files but are not displayed on the browser page. Comments are written for developers to explain the purpose, function, or special handling of the code.

Imagine you are reading a book, and the author has written some notes in the margins to help you understand certain paragraphs. HTML comments are these "margin notes" in the code.

Basic Syntax of Comments ​

html
<!-- This is a comment -->

<!-- 
  This is a
  multi-line comment
-->

<p>This text will be displayed</p>
<!-- This comment will not be displayed -->

Syntax Rules:

  • Start with <!--
  • End with -->
  • Content in between will be completely ignored by the browser
  • Can span multiple lines

Why Do We Need Comments? ​

1. Improve Code Readability ​

html
<!-- Website Navigation Bar -->
<nav>
  <ul>
    <li><a href="/">Home</a></li>
    <li><a href="/about">About</a></li>
    <li><a href="/contact">Contact</a></li>
  </ul>
</nav>

<!-- Website Main Content Area -->
<main>
  <!-- Article List -->
  <section class="articles">
    <!-- Each Article -->
    <article>
      <h2>Article Title</h2>
      <p>Article content...</p>
    </article>
  </section>
</main>

<!-- Website Footer -->
<footer>
  <p>Copyright Information</p>
</footer>

With comments, even if you look at the code months later, or other team members view the code, they can quickly understand the function of each part.

2. Team Collaboration ​

In team development, comments are an important tool for communication:

html
<!-- 
  Author: Alex Smith
  Date: 2025-11-29
  Description: This is the main layout for the product detail page
-->

<div class="product-detail">
  <!-- TODO: Add product rating feature - Alex -->

  <!-- FIXME: Image display issue on mobile - Sarah -->
  <img src="product.jpg" alt="Product Image" />

  <!-- NOTE: This component will be reused across multiple pages -->
  <div class="price-box">
    <span class="price">$99.99</span>
  </div>
</div>

Common Comment Tags:

  • TODO: Tasks to be done
  • FIXME: Issues to be fixed
  • NOTE: Important note
  • HACK: Temporary solution
  • WARNING: Warning information

3. Debugging Code ​

During development, comments can be used to temporarily disable code:

html
<!-- Temporarily hide this feature, pending design confirmation -->
<!--
<section class="new-feature">
  <h2>New Feature</h2>
  <p>This is a new feature...</p>
</section>
-->

<!-- Testing different layout schemes -->
<!-- Scheme 1: Temporarily disabled -->
<!--
<div class="layout-v1">
  ...
</div>
-->

<!-- Scheme 2: Currently in use -->
<div class="layout-v2">...</div>

4. Documentation ​

Comments can serve as code documentation:

html
<!-- 
  Product Card Component
  
  Features:
  - Display product image
  - Display product name and price
  - Provide "Add to Cart" button
  
  Dependencies:
  - styles/product-card.css
  - scripts/cart.js
  
  Usage Example:
  <div class="product-card" data-product-id="123">
    ...
  </div>
-->
<div class="product-card" data-product-id="123">
  <img src="product.jpg" alt="Product" />
  <h3>Product Name</h3>
  <p class="price">$99.99</p>
  <button>Add to Cart</button>
</div>

Scenarios for Using Comments ​

1. Marking Code Areas ​

html
<!-- ==================== Header Area Start ==================== -->
<header>
  <div class="logo">Logo</div>
  <nav>Navigation</nav>
</header>
<!-- ==================== Header Area End ==================== -->

<!-- ==================== Main Content Area Start ==================== -->
<main>
  <article>Content</article>
</main>
<!-- ==================== Main Content Area End ==================== -->

This method is particularly useful in large pages to quickly locate specific areas.

2. Explaining Complex Logic ​

html
<!-- 
  Used grid layout here instead of flexbox because 
  precise control of multi-dimensional alignment is needed
-->
<div class="complex-layout">
  <!-- Row 1: Three columns of equal width -->
  <div class="row">
    <div class="col">Item 1</div>
    <div class="col">Item 2</div>
    <div class="col">Item 3</div>
  </div>

  <!-- Row 2: Two columns, second column takes more space -->
  <div class="row">
    <div class="col sm">Item 4</div>
    <div class="col lg">Item 5</div>
  </div>
</div>

3. Version Control and Change Log ​

html
<!-- 
  Version History:
  v1.0 (2025-11-01): Initial Version - David
  v1.1 (2025-11-15): Added responsive support - Sarah
  v1.2 (2025-11-29): Optimized loading performance - Alex
-->
<div class="component-v1.2">...</div>

4. Temporary Data or Test Code ​

html
<!-- 
  Test Data:
  Use fake data in development environment
  Production environment will fetch real data from API
-->
<ul class="user-list">
  <!-- <li>Real User 1</li> Production Data -->
  <li>Test User 1</li>
  <!-- Test Data -->
  <li>Test User 2</li>
  <!-- Test Data -->
</ul>

5. Conditional Code ​

html
<!-- 
  IE specific handling code
  Modern browsers do not need this code
-->
<!--[if IE]>
  <link rel="stylesheet" href="ie-fixes.css" />
<![endif]-->

Note

Conditional comments are an IE-specific feature and are rarely used in modern development.

Best Practices for Comments ​

1. Comments should explain "Why", not "What" ​

html
<!-- ❌ Bad: Repeating code content -->
<!-- This is a paragraph tag -->
<p>Content</p>

<!-- This is a div -->
<div class="container">
  <!-- ✅ Good: Explaining reason and purpose -->
  <!-- Using div instead of semantic tags because this is a pure layout container -->
  <div class="layout-wrapper">
    <!-- 
  Keep this element empty,
  JavaScript will dynamically populate content
-->
    <div id="dynamic-content"></div>
  </div>
</div>

2. Keep Comments Concise and Clear ​

html
<!-- ❌ Bad: Too detailed -->
<!-- 
  This button is a button element used to submit the form,
  when the user clicks this button, the form will be submitted to the server,
  the server will process the form data, and then return the result,
  the user will see a success message...
-->
<button type="submit">Submit</button>

<!-- ✅ Good: Concise and clear -->
<!-- Form submit button -->
<button type="submit">Submit</button>

3. Update or Delete Outdated Comments Promptly ​

html
<!-- ❌ Bad: Outdated comments -->
<!-- Used jQuery for carousel here -->
<!-- Actual code has switched to Vue component -->
<div class="carousel-vue-component">
  <!-- ✅ Good: Keep comments in sync with code -->
  <!-- Vue carousel component, supports autoplay and touch swipe -->
  <div class="carousel-vue-component"></div>
</div>

4. Use Consistent Comment Style ​

Teams should unify comment styles:

html
<!-- Style 1: Short comments -->
<!-- Navigation Bar -->
<nav>...</nav>

<!-- Style 2: Separator style -->
<!-- ==================== Navigation Bar ==================== -->
<nav>...</nav>

<!-- Style 3: Block comment style -->
<!-- 
  Navigation Bar
  Contains main menu and user menu
-->
<nav>...</nav>

Choose one style and maintain consistency throughout the project.

5. Avoid Commenting Out Large Blocks of Code ​

html
<!-- ❌ Bad: Commenting out large blocks of old code -->
<!--
<div class="old-layout">
  <div class="old-header">
    <h1>Old Title</h1>
    ... 100 lines of old code
  </div>
</div>
-->

<!-- ✅ Good: Use version control system -->
<!-- 
  Old layout removed, see Git commit abc123
  To restore, check code before 2025-11-01
-->

Use version control systems like Git to manage code history instead of keeping large blocks of commented-out code in files.

6. Pay Attention to Comment Visibility ​

html
<!-- âš ī¸ Warning: Comments are visible in source code -->
<!-- 
  Do not include sensitive information in comments!
  API Key: 12345 ❌ Error
  Password: password ❌ Error
-->

<!-- ✅ Correct Practice -->
<!-- 
  Refer to config/api.js for API configuration
  Do not hardcode keys in HTML
-->

Although comments are not displayed on the page, anyone can see them using the "View Source" feature.

Advanced Applications of Comments ​

1. Component Documentation ​

html
<!-- 
  [Button Component]
  
  Types:
  - primary: Primary action button (Blue)
  - secondary: Secondary action button (Gray)
  - danger: Danger action button (Red)
  
  Sizes:
  - sm: Small button
  - md: Medium button (Default)
  - lg: Large button
  
  Example:
  <button class="btn btn-primary btn-lg">Large Primary Button</button>
-->
<button class="btn btn-primary">Confirm</button>
<button class="btn btn-secondary">Cancel</button>

2. Performance Optimization Notes ​

html
<!-- 
  Performance Optimization:
  - This image uses lazy loading
  - Loads only when scrolled into viewport
  - Uses Intersection Observer API
-->
<img
  src="placeholder.jpg"
  data-src="real-image.jpg"
  alt="Product"
  class="lazy-load"
/>

<!-- 
  Critical CSS Inline:
  For first paint performance,
  inline first paint styles directly in head
-->

3. Browser Compatibility Notes ​

html
<!-- 
  Compatibility Note:
  - This feature is not supported in IE11
  - Fallback provided
  - See polyfills/grid-fallback.js
-->
<div class="grid-layout">
  <!-- Using CSS Grid Layout -->
</div>
html
<!-- 
  SEO Optimization:
  - Title length controlled within 60 characters
  - Description length controlled within 160 characters
  - Contains target keyword "Frontend Development"
-->
<head>
  <title>Frontend Development Guide - Frontend Knowledge Station</title>
  <meta name="description" content="..." />
</head>

Special Purpose Comments ​

1. Conditional Comments (Legacy) ​

html
<!-- Visible only to IE -->
<!--[if IE]>
  <p>You are using Internet Explorer</p>
<![endif]-->

<!-- IE 10 and above -->
<!--[if gte IE 10]>
  <p>IE 10+</p>
<![endif]-->

Note

Conditional comments are only valid in IE 9 and earlier, modern browsers do not support them. This is a legacy feature and should not be used in new projects.

2. Template Engine Comments ​

Different template engines have their own comment syntax:

html
<!-- Vue.js -->
<!-- Vue component comment -->

<!-- React JSX -->
{/* JSX comment */}

<!-- Angular -->
<!-- Angular component comment -->

Common Mistakes and Pitfalls ​

Mistake 1: Nested Comments ​

html
<!-- ❌ Error: Comments cannot be nested -->
<!-- Outer comment
  <!-- Inner comment -->
End -->

<!-- ✅ Correct: Single layer comment -->
<!-- 
  This is a comment
  Can be multi-line, but cannot be nested
-->

Principle: The HTML parser considers the comment ended when it encounters the first -->, and cannot correctly handle nesting.

Mistake 2: Special Characters in Comments ​

html
<!-- ❌ May cause issues -->
<!-- Using -- separator -->

<!-- ❌ May cause issues -->
<!-- Show discount when price > 100 -->

<!-- ✅ Correct: Avoid using -- -->
<!-- Using hyphen separator -->

<!-- ✅ Correct: Use text description for special characters -->
<!-- Show discount when price is greater than 100 -->

Note: HTML specification does not allow -- in comments. Although most browsers can handle it tolerantly, it should be avoided.

Mistake 3: Using HTML Comments in Scripts and Styles ​

html
<!-- ❌ Bad: Using HTML comments in script -->
<script>
  <!--
  console.log("Hello");
  -->
</script>

<!-- ✅ Good: Using correct comment syntax -->
<script>
  // JavaScript comment
  /* Multi-line comment */
  console.log("Hello");
</script>

<style>
  /* CSS comment */
  .class {
    color: red;
  }
</style>

Tool Support for Comments ​

1. VS Code Shortcuts ​

  • Add comment: Ctrl + / (Mac: Cmd + /)
  • Remove comment: Press Ctrl + / again
  • Block comment: Shift + Alt + A (Mac: Shift + Option + A)

2. Comment Folding ​

Modern editors support folding comment areas:

html
<!-- #region Navigation Bar -->
<nav>
  <!-- Navigation Content -->
</nav>
<!-- #endregion -->

3. Generating Documentation ​

Some tools can generate documentation from comments:

html
<!-- 
  @component ProductCard
  @description Product Card Component
  @author Alex Smith
  @version 1.0.0
-->
<div class="product-card">...</div>

When NOT to Use Comments ​

1. Self-explanatory Code ​

html
<!-- ❌ Unnecessary comments -->
<!-- Product List -->
<ul class="product-list">
  ...
</ul>

<!-- ✅ Class name is clear enough -->
<ul class="product-list">
  ...
</ul>

If the code itself is clear enough, comments are not needed.

2. Code That Should Be Refactored ​

html
<!-- ❌ Using comments to compensate for bad code -->
<!-- 
  This div is actually a button,
  but used div due to styling issues
-->
<div onclick="submit()">Submit</div>

<!-- ✅ Refactor Code -->
<button onclick="submit()">Submit</button>

If you need comments to explain "why it is written this way", it may indicate that the code needs refactoring.

Practical Exercise ​

Add appropriate comments to the code below:

html
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My Website</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <header>
      <nav>
        <ul>
          <li><a href="/">Home</a></li>
          <li><a href="/about">About</a></li>
        </ul>
      </nav>
    </header>

    <main>
      <article>
        <h1>Article Title</h1>
        <p>Article content...</p>
      </article>
    </main>

    <footer>
      <p>&copy; 2025 My Website</p>
    </footer>
  </body>
</html>

Reference Answer:

html
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My Website</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <!-- ========== Page Header ========== -->
    <header>
      <!-- Main Navigation Menu -->
      <nav>
        <ul>
          <li><a href="/">Home</a></li>
          <li><a href="/about">About</a></li>
        </ul>
      </nav>
    </header>

    <!-- ========== Main Content Area ========== -->
    <main>
      <!-- Article Content -->
      <article>
        <h1>Article Title</h1>
        <p>Article content...</p>
      </article>
    </main>

    <!-- ========== Page Footer ========== -->
    <footer>
      <!-- Copyright Information -->
      <p>&copy; 2025 My Website</p>
    </footer>
  </body>
</html>

Summary ​

This lesson covered comprehensive knowledge of HTML comments:

  1. Basic Syntax: <!-- Comment Content -->
  2. Purpose:
    • Improve code readability
    • Facilitate team collaboration
    • Assist debugging
    • Document code
  3. Best Practices:
    • Explain "Why", not "What"
    • Keep concise and clear
    • Update or delete outdated comments promptly
    • Use consistent style
    • Avoid commenting sensitive information
  4. Common Pitfalls:
    • Cannot nest comments
    • Avoid using --
    • Comments are visible in source code
  5. When Not to Use:
    • Self-explanatory code
    • Code that should be refactored

Core Principles:

  • Good comments make code easier to maintain
  • Comments should supplement code, not repeat code
  • Code first, comments are just auxiliary