HTML Comments
HTML comments are used to insert notes or explanations in the source code that are not displayed in the browser. They help developers document code, explain complex sections, or temporarily disable certain parts without deleting them. Comments begin with <!--
and end with -->
.
Key Topics
Comment Syntax
Comments are not displayed by the browser and do not affect rendering. Below are simple examples of how to use comments.
Example: A single-line comment providing a note to developers.
<!-- This is a comment -->
Example: A multi-line comment can explain complex code.
<!--
This is a multi-line comment.
It can provide longer explanations.
-->
Example: Comments can temporarily disable code without removing it.
<!-- <h1>Temporarily removed heading</h1> -->
Basic Page Structure Example
This example shows how comments can be integrated into a simple HTML page. Since this is a full HTML code demonstration, it is enclosed in a copy code box.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page with Comments</title>
</head>
<body>
<!-- Main heading of the page -->
<h1>Welcome to My Site</h1>
<p>This paragraph introduces the site to visitors.</p>
<!-- This link is not needed right now, uncomment when ready
<a href="https://example.com">Visit Example</a>
-->
<p>Comments can explain code to help developers understand its purpose.</p>
</body>
</html>
Explanation: The comments in the code describe the purpose of the heading and explain why the link is currently commented out. This helps maintainers understand the code's intention and consider future modifications more easily.
More Complex Example: Tables
Comments can also be used within tables to note data sources, explain columns, or plan future enhancements. Below is another code-box demonstration.
<h2>Product Data</h2>
<!-- Next table shows the product inventory -->
<table border="1" style="border-collapse:collapse;">
<!-- Table header -->
<tr>
<th>Product</th>
<th>Quantity</th>
</tr>
<!-- Inventory rows -->
<tr>
<td>Laptop</td>
<td>10</td>
</tr>
<tr>
<td>Mouse</td>
<td>50</td>
</tr>
<!-- Future enhancement: Add price column -->
</table>
Explanation: The comments in the table code clarify what each part represents and hint at future additions (like a price column). Such notes guide developers when they revisit the code later.
Key Takeaways
- Use comments to explain code, making it easier for developers to understand and maintain.
- Comments are invisible to users, do not affect page rendering, and provide context for future improvements.
- They can temporarily disable code without deleting it.
- Concise, clear comments improve collaboration and long-term maintainability.
- Use comments strategically to clarify complex logic, annotate data structures, or highlight pending tasks.