HTML Comments

Shows how to write HTML comments, and offers advice on when (and when not) to use comments in HTML markup.

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.

You cannot nest HTML comments — that is, you can't place one HTML comment inside another.

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">
    <li><a href="/">Home</a></li>
    <li class="hi"><a href="/about/">About</a></li>

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.

HTML comments and JavaScript

In the "olden days" (i.e. the late 1990s), some browsers couldn't recognize JavaScript code in Web pages. It was therefore necessary to "hide" JavaScript from these browsers by using HTML comments:

... (JavaScript code here) ...
// -->

These days there's no need to comment JavaScript like this — in fact it can cause more problems than it solves. Instead, simply write:

<script type="text/javascript">
... (JavaScript code here) ...

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!

Follow Elated

Related articles

Responses to this article

There are no responses yet.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page