Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

Comments – HTML

Summary

Syntax:

<!--  -->

Single line comment:

<!-- This is a comment in HTML -->

Multi-line comment:

<!--
  This is also
  a comment in HTML
-->

Details

Comments in HTML allow you to write notes to yourself about the code you’ve written. You can use them to quickly explain what parts of your code do. They can also serve as helpful reminders for what your code does when you revisit the project in the future. The text inside a comment will not show up on the actual web page.

A comment starts with an opening angle bracket, an exclamation point, and two dashes.

<!-- 

The text you want to include in the comment goes next.

<!-- This is a comment in HTML

Usually there is a space at the beginning and end of the text to improve readability. It ends with two dashes and a closing angle bracket.

<!-- This is a comment in HTML -->

As you can see from the examples in the Summary, comments can span a single line or multiple lines.

Disabling code

Comments can also be used to temporarily disable sections of code, so you can see what your web page looks like without a particular element or group of elements. Here’s an example of a paragraph element that’s been commented out:

<!-- <p>This paragraph text won't show when it's in a comment.</p> -->

If you decide that you don’t need the code that you’ve commented out, it’s best to delete the code rather than leave it in so you don’t end up with a bunch of commented out code in your HTML file.

Common problems

Generally speaking, you can’t have a comment inside another comment in HTML. Here’s an example:

<!-- Here's the start of the first comment
  <!-- This comment is nested inside the other comment -->
Here's the end of the first comment (careful: this line will appear on the web page!) -->

The last line of the comment will appear on the web page. The reason why is that the closing part of the inner comment acts as the closing part of the outer comment as well.

VS Code Tip

To quickly create a comment in VS Code, press Ctrl + / on Windows or Cmd + / on macOS. This will create a new comment on a blank line or comment out the line your cursor is on if there is already code on it.

You can also use an Emmet shortcut to create a comment. Type c and then press Enter or Tab to generate a comment.

Demo

Exercises

Recreate the code snippet in the Demo section by typing out the code in your index.html file.

References

Getting Started with HTML on MDN

Lesson tags: Open Lesson
Back to: HTML Reference > HTML Syntax