3.8 We Should Use HTML Comments More
I have a terrible memory. I can barely remember what I did yesterday, or if I locked the door, or if I actually turned on the alarm on my alarm clock, or if I just thought I did. The life of a Brain Genius is hard. So it’s only natural that when I look at something I coded for myself months or years ago, I usually have no idea what does what. Thankfully, my div classes are usually pretty intuitively named. I can usually figure out what does what in my HTML without using HTML comments, but using HTML comments more often would make my life so much easier.
For those unfamiliar with HTML comments, they are text written inside an HTML comment tag. Here’s an example of one of mine with some of my Tumblr URLs censored so I don’t embarrass myself.
To write an HTML comment, you type <!– and then whatever text you want before closing the tag by typing –>. Part of what makes HTML comments so useful and so unique is, as Jennifer Kyrnin explains in her 2019 Lifewire post “How and Why to Add Comments in Your HTML“, HTML comments do not show up in the web browser when visitors visit your site. HTML comments only show up “when someone views the source of a web page or opens the HTML in an editor.” You can see this for yourself in the following screenshot of the theme I mentioned in the previous screenshot’s caption.
“Okay cool,” you might be saying, “but why or how should I use HTML comments in my HTML?” Excellent question. For starters, you can use it to temporarily “turn off” portions of your HTML when you’re testing or developing a page. As Kyrnin explains, “If you add the opening part of a comment directly before the part of your page/code that you want to hide, and then you add the closing part at the end of that code…then whatever HTML elements that fall within that comment will no longer be displayed in the browser.” That means that part of your code will remain in your code, but it won’t be displayed, which is better than deleting it. If that portion of the code isn’t the one causing a problem, you can just remove the HTML comment tags.
In addition, as Kyrnin points out, you can comment to document any aspect of your code you want. Here’s a list of how I personally have used HTML comments in the past:
- To credit myself, others, and resources I have used to code things.
- To label where HTML elements begin and where they end.
- To indicate what type of post or block is governed by that section of HTML.
- To label what div classes are contained inside a larger div class.
- To remind myself what I’m doing or trying to obtain with a certain portion of HTML.
HTML comments are incredibly versatile and very easy to use and implement, but many people (including myself) don’t use them as much as we should, so let’s change that. After all, they’re a tool that’s useful for developers and coders of any level.
This chapter is a revised version of a blog post titled “We Should Use HTML Comments More” on Digital Media Miscellany.