Topic 40 of 41
Comments in HTML
Overview
Comments are notes you leave in your code for yourself or other developers. The browser completely ignores them; they will NEVER show up on the actual web page.
We use comments to explain why a piece of code exists, to divide long documents into readable sections, or to temporarily disable a chunk of code without deleting it (called 'commenting out' code).
Syntax
An HTML comment starts with `<!--` and ends with `-->`. Anything in between those markers is completely invisible to the user on the screen.
Writing Comments
html
<!-- This is a comment. The browser ignores me! -->
<p>This is a real paragraph.</p>
<!--
You can also write multi-line comments.
This is great for long explanations.
-->If a feature is broken or you want to hide it temporarily for testing, don't delete the code! Just wrap it in a comment.
Commenting Out Code
html
<div>
<h2>Winter Sale!</h2>
<!-- Temporarily hiding the discount button until Friday -->
<!-- <button>Get 50% Off</button> -->
</div>Common Pitfalls
- Comments are invisible on the screen, but they are NOT secret! Anyone can right-click the page, click 'View Page Source', and read all your comments. Never put passwords, API keys, or angry notes about your boss in HTML comments.
- You cannot nest comments inside other comments. `<!-- <!-- nested --> -->` will break your code.
Real-World Example
Using comments to organize a large HTML file:
example
html
<!-- ============================== -->
<!-- HEADER & NAVIGATION SECTION -->
<!-- ============================== -->
<header>
<nav>...</nav>
</header>
<!-- ============================== -->
<!-- MAIN HERO SECTION -->
<!-- ============================== -->
<section id="hero">
<h1>Welcome</h1>
</section>