Like many programming languages, HTML lets you embed comments within your Web pages. A comment is a piece of text intended just for people to read; Web browsers ignore any HTML comments embedded in a page.
How to write HTML comments
You insert an HTML comment like this:
<!-- This is an HTML comment -->
You can also spread comments over many lines, like this:
<!-- Here's a really, really long HTML comment over several lines. -->
Generally you can put any text you like in an HTML comment. However, for compatibility reasons, never place
-- (2 hyphens together) anywhere within the comment text itself.
When to use HTML comments
HTML comments are a great way to make your markup more readable — both for yourself and for other coders. However, don’t put too many HTML comments in a page, since each comment adds to the page size (and therefore its download time).
You can use a comment to clarify the purpose a complex piece of code. For example:
<!-- Navigation area: Highlight a menu item with the "hi" class --> <div id="nav"> <ul> <li><a href="/">Home</a></li> <li class="hi"><a href="/about/">About</a></li> </ul> </div>
Comments are also useful for those times when you need to add an unusual piece of markup:
<!-- 99.9% width works around an IE6 rounding bug --> <div style="width: 99.9%">
You can also use HTML comments to “comment out” a section of markup temporarily. This causes the browser to skip that section of HTML — handy for testing and debugging your page in different browsers:
<!-- <img src="images/pic.jpg" alt="Pic" /> -->
However, if you want to disable a section of markup on a more permanent basis it’s better to remove it from the page entirely. Also, remember that you can’t nest HTML comments, so you can’t comment out a section of HTML that itself contains comments.
You now know how to create HTML comments, and you’ve looked at when (and when not) to place comments in your HTML pages. Happy coding!
Leave a Reply