How to write comments inside HTML documents

You can write comments in your HTML document by using the special comment tag that consists of the opening tag <!-- and the closing tag -->.

Any text you write inside the comment tag will be hidden from the web page:

<body>
  <h1>Comment in HTML</h1>
  <!-- This is a comment -->
  <p>Hello world!</p>
</body>

The commented text above won’t appear on the page when you open it using the browser.

However, you can still see the comment from the developer console or the source page:

You can also create a multi-line comment when you have a long line of text as shown below:

<body>
  <h1>Comment in HTML</h1>
  <!-- 
    Here is an example
    of a multi-line comment
    You can have as many lines of comment as you need
  -->
  <p>Hello world!</p>
</body>

You can also use the comment tag to hide any HTML element that you don’t want to be displayed on the browser.

The following example comments out the <button> element from the page:

<body>
  <h1>Commenting elements in HTML</h1>
  <p>Hello world!</p>
  <!-- 
    <button>Learn more</button>
  -->
</body>

But since the HTML source is accessible from the browser HTML inspector, any informed user can open the inspector to remove your comment tag and display the <button> on the page.

Still, commenting on HTML elements is useful when you need to narrow your focus when debugging or modifying the HTML markup.

Comments are generally used for informing other web developers about a specific part of the document that requires attention.

For example, you may remind fellow developers about an image that needs to be uploaded for the <img> tag to work:

<body>
  <h1>Hello World</h1>
  <!-- 
    TODO: Add the src image to the folder and fill the alt description
  -->
  <img src="image.png" alt="">
</body>

Finally, keep in mind that the HTML comment tag is only valid for HTML markups.

If you want to comment out a part of the CSS <style> tag that you write in your HTML markup, then you need to use the CSS comment pattern.

The following example won’t work:

<style>
<!--
  html {
    background-color: red;
  }
-->
</style>

You need to use the CSS comment pattern /* ... */ inside HTML <style> tag as shown below:

<style>
/*
  html {
    background-color: red;
  }
*/
</style>

The same also applies to JavaScript code inside your <script> tag. It must be commented using the JavaScript comment pattern:

<script>
  // document.write("Hello World!");
</script>

And that’s how HTML comment works.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.