HTML Comments
In HTML, comments are notes or explanations that you add inside the code. They are not displayed on the webpage because the browser ignores them. Useful for documentation, explanations, debugging, and temporarily hiding code.
Syntax
This is a comment .
-->
Valid vs Invalid Comments
When we talk about valid and invalid comments in programming or HTML, we mean whether the comment follows the correct rules of writing it.
Valid comments
These are written using the proper syntax, so the computer understands that it’s a comment and ignores it. For example, in HTML: This works because it starts with <!--
and ends with -->
, exactly as it should.
This is a valid comment .
-->
Invalid comments
These don’t follow the correct syntax, so the computer doesn’t treat them as comments. Instead, they might show up as normal text on the webpage or even cause errors. For example:This is wrong because there’s a space after <
, so the browser doesn’t recognize it as a proper comment.
Uses of Comments
- For notes in your code (easy to understand later).
- To hide code temporarily without deleting it.
- To debug by disabling certain parts of HTML.
Single-line Comment
A single-line comment is used to comment out one line in HTML.
It starts with <!--
and ends with -->
.
This is a Single-line Comment.
-->
Multi-line Comment
If you want to write comments in multiple lines, you can wrap your text inside the same <!--
and --.>
This is a multi-line comment.
You can write notes here.
It won’t show in the browser.
-->
Commenting Script Code
Sometimes, an HTML page contains JavaScript or VBScript. In older browsers, these scripts might not run correctly and could even be shown as plain text on the page. To avoid this problem, developers used to place the script code inside HTML comment tags. This way, the browser would ignore the script as normal text if it didn’t understand it, but newer browsers that supported JavaScript would still run it properly.
// This is a single-line JavaScript comment
/*
This is a multi-line
JavaScript comment
*/
</script>
Commenting Style Sheets
When writing CSS (Cascading Style Sheets), you can add comments to explain your code, make notes, or temporarily disable certain styles. These comments do not affect how the page looks in the browser — they are ignored when the styles are applied.
/* This is a CSS comment */
p {
color: blue;
}
</style>