HTML Comment


What is Comment in HTML?

Comments are just words or sentences, that humans read but the browser skips, what we can write in the source code using comment tag.But like other elements,it is not shown onscreen. Comments can be seen only in the source code.

Syntax of HTML Comment tags-

Fig.1 - diagram of HTML comment tags

In the above picture you can see anything between <!-- and --> is called as comment.

are comments useful?

Comments are very useful. If you use comments then no matter what you'll never forget why you wrote this line of code. Also if you read someone else's code then you'll easily understand that too. Thus we can save the time. As well as comments work as a reminders. Lets see the examples-

Example of HTML comments-

<!DOCTYPE html>
<html>
 <head> <!-- start of head tag -->
   <meta charset=”UTF-8”>
   <title>Example of HTML comment tags </title>
 </head>  <!-- End of head tag -->
 <body>   <!-- start of body tag -->
  <p> My first paragraph. </p>
 </body> <!-- End of body tag -->
</html>

Result

html-comment-element-grphics
Fig.2 - Example of HTML comment tag

In the above example you can see we use so many comment tags and it's useful so that we can see later whether or not we forget to close the elements.

More Example of HTML comments-

<!DOCTYPE html>
<html>
<head>
 <meta charset=”UTF-8”>
<title>Example of HTML comment tags </title>
</head>
<body>
<p> My first paragraph. </p>
<!-- we have to show this later
<p>My second paragraph.somthing important.</p>
-->
</body>
</html>

Result

html-comment-element-grphics
Fig.3 - Example of HTML comment tag

Notice that here we have a p element inside of comment tags that's why you can't see it onscreen. If you'll come back later It'll work like a reminders that something you have to change.

Multiline Comments-

In HTML you can comment multiple lines of code too. It is so easy. First write <!-- then anything that you want to comment then write -->. See the example below-

Example of HTML Multiline Comments-

<!DOCTYPE html>
<html>
 <head>
  <meta charset=”UTF-8”>
  <title>Example of HTML Multiline comments </title>
 </head>
 <body>
 <!--this
 is
 a
 paragraph
 -->
  <p> My first paragraph. </p>
 </body>
</html>

Result

html-comment-element-grphics
Fig.4 - Example of HTML Multiline comment

It'll produce the same result.

Invalid comment in HTML

You should not have any space between < and ! if you do so then it'll not work as comment.see the example below-

<!DOCTYPE html>
<html>
<head>
 <meta charset=”UTF-8”>
 <title>Example of HTML Multiline comments </title>
</head>
<body>
< !--this is a invalid comment.-->
 <p> My first paragraph. </p>
</body>
</html>

Result

html-comment-element-grphics
Fig.5 - Example of HTML invalid comment-

In the above example we can see having a space between < and ! the browser does not ignore it.