HTML comments are used to leave notes within the HTML code that won’t be displayed on the web page itself. They are useful for explaining the code, leaving reminders, or temporarily disabling code during development. Comments in HTML start with <!-- and end with -->.

Basic Syntax

The basic syntax of an HTML comment is:
				
					<!-- This is a comment -->

				
			

Usage Examples

Example 1: Adding Notes

You can add notes within your HTML code to explain certain parts or leave reminders for yourself or other developers.
				
					<!DOCTYPE html>
<html>
<head>
    <title>Comment Example</title>
    <!-- The title of the page goes here -->
</head>
<body>
    <h1>Welcome to My Website</h1>
    <!-- This is the main header -->
    <p>This is a paragraph of text.</p>
    <!-- Remember to add more content here -->
</body>
</html>

				
			

Example 2: Disabling Code

Sometimes, you might want to disable a section of your code without deleting it. You can comment it out.
				
					<!DOCTYPE html>
<html>
<head>
    <title>Comment Example</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <!--
    <h2>This is a secondary header that is temporarily disabled</h2>
    -->
    <p>This is a paragraph of text.</p>
</body>
</html>

				
			
In this example, the ‘<h2>‘ header will not be displayed because it is commented out.

Example 3: Hiding Scripts

You can use comments to hide script content from browsers that do not support scripting.
				
					<!DOCTYPE html>
<html>
<head>
    <title>Comment Example</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <p>This is a paragraph of text.</p>
    <!--[if lt IE 9]>
    <script src="some-script-for-old-IE.js"></script>
    <![endif]-->
</body>
</html>

				
			
In this example, the script is only executed if the browser is Internet Explorer 9 or lower.

Example 4: Commenting Out Large Sections

If you need to temporarily remove a large section of code, you can comment it out.
				
					<!DOCTYPE html>
<html>
<head>
    <title>Comment Example</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <!--
    <div>
        <h2>This is a section that is currently disabled</h2>
        <p>It contains multiple elements.</p>
    </div>
    -->
    <p>This is a paragraph of text.</p>
</body>
</html>

				
			
In this example, the entire ‘<div>‘ section is commented out and will not be rendered.

Best Practices

  • Clarity: Use comments to make your code more understandable. Explain the purpose of complex code or sections.
  • Maintainability: Update comments when you update code to ensure they remain accurate.
  • Simplicity: Avoid over-commenting. Only comment on parts of the code that need explanation.
HTML comments are a simple yet powerful tool for improving the readability and maintainability of your HTML documents. Use them wisely to make your code more understandable and easier to manage.
Scroll to Top