Introduction to HTML Comments

HTML comments are not displayed in the browser but can help document your HTML source code. They are written with the following syntax:

<!-- This is an HTML comment -->

Comments are essential for explaining your code, making it more readable for yourself and other developers. They can also be used to temporarily disable code without deleting it.

Note: While comments are useful, avoid over-commenting. Good code should be self-explanatory whenever possible.

Practical Uses of Comments

1. Code Documentation

<!-- Main navigation starts here -->
<nav>
  <!-- Home link -->
  <a href="/">Home</a>
  
  <!-- About link -->
  <a href="/about">About</a>
</nav>
<!-- Main navigation ends here -->

2. Commenting Out Code

<!-- Temporarily disabled section
<div class="advertisement">
  <p>Special offer this week!</p>
</div>
-->

3. Conditional Comments (Legacy)

<!--[if IE]>
  <p>This content is only visible in Internet Explorer</p>
<![endif]-->

Note: Conditional comments were only supported in IE and are now obsolete.

Multi-line Comments

<!-- 
  This is a multi-line HTML comment.
  You can write as many lines as needed.
  Useful for longer explanations or
  temporarily disabling large code blocks.
-->

Best Practices

  • Use comments to explain complex structures, not obvious code
  • Keep comments concise but meaningful
  • Update comments when you update the corresponding code
  • Use consistent comment formatting throughout your project
  • Remove debugging comments before production
  • Avoid commenting out large blocks in production code
  • Consider using version control instead of commented-out code

Important Notes

Security Considerations

  • Comments are visible in page source (View Source)
  • Never put sensitive information in comments
  • Search engines may index commented content

Performance Impact

  • Excessive comments increase page size
  • Minifiers typically remove comments during build
  • Comments don't affect rendering performance