HTML & CSS
Article

How Good Are Your HTML and CSS Comments?

By Georgie Luhur

One of the things you usually learn when you start learning about basic HTML or CSS is how to write comments in your code. However, many web developers still don’t use comments to their advantage. We may use comments widely in HTML and CSS, but when written properly, and with intent, they can really improve our workflow.

When you start working at a new company, looking at manuals or many pages of documentation can be daunting. Every company is different – meaning that the codebases, amount of legacy code, development of frameworks, and amount of modular code can be different.

We’re often told that “good code doesn’t need comments”, but do you ever find yourself going around in circles, completely lost, and searching for documentation because of a lack of comments?

Two Facts About Code Comments

  1. Comments are ignored by the browser.
  2. Comments are stripped out during minification.

Based on these two facts, we know that comments are not really meant for machines – they are meant for humans to read.

Why Commenting Code Is Important

When you are freelancing and working on a solo project, or when you are the only developer who is going to be looking at your code, it’s easy to go about it your own way and make comments as you see fit, or maybe leave no comments at all. But a lot of the time, developers say that they look back at their own code and wonder, “What was I thinking?” or struggle to understand that code they have written.

Comments can help maintain consistency. If you have consistent, well-written comments for what you are building then you are more likely to build things the same way each time.

Comments facilitate understanding. This is really important in a team where sometimes one person does not do all the work. You might write comments to help yourself figure out some logic, and even though you do not keep all of your comments by the end of the project, it can help you better understand how you came to a solution. It can help you improve on that solution much more easily later on.

Commenting can also assist with hotfixes or quick fixes. Comments can actually help in three ways here. They can help developers understand the code if they need to make a quick fix (especially developers outside of the front-end team who may be helping out), it can help by marking out where these fixes are needed, and can show where quick fixes have been applied and need to be removed at some point.

Comments help speed up the development process. You can have a clearer understanding of what you are creating, changing or removing if you include relevant comments.

Comments facilitate more efficient collaboration. If you know the ins and outs of a project or codebase, you are more likely to get bits and pieces done quicker, thus improving workflows.

Comments help a lot of people. They not only help yourself, but they can help other people in your team. Gone are the days that we saw comments like DO NOT STEAL MY CODE in people’s source code. While we used to be very protective of our code, not wanting to share our ‘secrets’, we now live in a world where people share code, work on projects together and collaborate. We are not ashamed of crediting the likes of Harry Roberts, Chris Coyier or Jonathan Snook when it comes to web projects. With this shift in collaboration, we should also take note of our commenting practices – and help our peers.

Some Things to Avoid When It Comes to Comments

Avoid Commenting Absolutely Everything

It may be tempting to get into the habit of commenting every block of code, but this can be more redundant than useful or helpful. Commenting should only be done where something may not be completely clear. If you considered semantics when naming your classes, your code may already be easy to understand.

This may also be where the concept of “good code does not need comments” came from. Comments should not be completely avoided, but only used where necessary.

Do Not Be Too Verbose

I am personally guilty of writing some rather long comments in my CSS, because I love explaining and documenting things. However, you shouldn’t be writing novels – long comments are as much a pain to read as they can be to write. If you can be succinct, do so. Sometimes, when naming CSS classes, the following advice is given:

Make class names as short as possible but as long as necessary.

The same applies to comments. It’s good to read over any comments you write to ensure that you understand them yourself. Imagine you are someone new to the code and you are reading the comments as a guide.

Do Not Spend Too Much Time Writing Comments

I once saw a file in a project I was working on that had a line at the top reading:

// Update this with how many hours you have spent on this file:
// TIME_WASTED = 438;

You shouldn’t need to spend a lot of time writing comments. A few words is usually enough. If you are spending too much time trying to comment your code to make sure someone else will understand it, consider that parts of your code might actually need refactoring.

Some Examples of When to Use Comments

To Explain a Pseudo Element’s Purpose

This example shows a pseudo element with the content value filled in.

.post__comment-container::after {
  background-color: #f9f9f9;
  border: 1px solid #dedede;
  border-radius: 0.25em;
  color: #888;
  content: 'Post author';
  display: inline-block;
  font-size: 0.7rem;
  margin-left: 0.5rem;
  padding: 0.2rem 0.45rem;
  vertical-align: middle;
}

It may not be immediately clear what a pseudo element is for, especially if the content property is displayed as content: ''. With a short comment above the code block, we can improve this.

/* Post author label for comment */

.post__comment-container::after {
  background-color: #f9f9f9;
  border: 1px solid #dedede;
  border-radius: 0.25em;
  color: #888;
  content: 'Post author';
  display: inline-block;
  font-size: 0.7rem;
  margin-left: 0.5rem;
  padding: 0.2rem 0.45rem;
  vertical-align: middle;
}

To Explain a Nested Code Block

While it definitely helps to use semantic classes as much as possible, it may not always be clear why a block of CSS would be nested when using a preprocessor:

.c-segment-controls.is-active {
  .c-segment-controls__panel {
    background-color: #fafafa;
    border: 1px solid #aaa;
    opacity: 1;
    transition: opacity 0.5s ease;
  }
}

Six words is enough for a comment to indicate what this code block does, allowing someone to be able to skim the document and either stop or skip ahead.

.c-segment-controls.is-active {

  /* Active state for segment controls panel */

  .c-segment-controls__panel {
    background-color: #fafafa;
    border: 1px solid #aaa;
    opacity: 1;
    transition: opacity 0.5s ease;
  }
}

To Explain Why !important Might Be Needed

We often see !important and assume we are looking at legacy code or a dirty hack:

.c-accordion-container.ng-hide {
  display: block !important;
}

Upon closer inspection, we’re just overriding a framework’s default behavior.

/**
 * Overriding some rogue Angular code.
 * Forces `display: block` so that the element can be animated.
 */

.c-accordion-container.ng-hide {
  display: block !important;
}

To Explain Why a Code Block Was Commented out Rather Than Simply Deleted

If we look at the code block below, we might assume deleting this is fine. Surely it isn’t being used anywhere? If I delete it, it will be in version control anyway when we need it later, right?

// .c-segmented-button__icon {
//   transform: translateY(calc((40px - 100%)/2));
// }

But if we delete it, someone might not even know it existed in the first place. It might be a good idea to leave this here:

/**
 * Calculation for vertical alignment.
 * Can be used when IE11 support is dropped.
 */

// .c-segmented-button__icon {
//   transform: translateY(calc((40px - 100%)/2));
// }

Other Kinds of Documentation

Documentation is really important and not just limited to comments in code. When we are done with a task, we might get it peer reviewed.

Commit Messages

When using version control (for example, Git), we can take what we know about writing useful comments in code and apply this to our commit messages.

Bad commit messages do not give much context. They look sloppy, and can be hard to understand. They are not helpful for release notes. It can be hard for a developer to know what has changed. Bad commit messages often look like this.

commit 2faa2
    wip
commit 591ad
    tried to fix some weird box
commit af830
    made the triangle thing work
commit bd02a
    refactor
commit bed4b
    hotfix navigation
commit 22fe0
    oops

A better example would describe, using a verb, the task completed in a commit. Different minor tasks would be spread out across different commits.

commit 2faa2
    Adding form component housing
commit 591ad
    Fixing box-sizing issue
commit af830
    Implementing triangle for notification bubble
commit bd02a
    Refactoring list item for smaller viewports
commit bed4b
    Fixing navigation float issue
commit 22fe0
    Fixing typos in class names

Karma has a pretty simple guide to writing better commits, whereas Chris Beams has a very in-depth guide. David Demaree even wrote an article titled ‘The Art of the Commit’. Commit messages definitely deserve some attention.

Pull Requests

After writing a handful of commits, you usually create a pull request for one of your peers to look at. I’ve seen one too many pull requests that have very little detail or no description at all:

An example of a poorly written pull request

When you are writing a pull request you are usually expecting someone to review your code. To assist that person and help ease the process, you should write a description of what the pull request includes. This is my mental checklist:

  • Ticket number, task number or issue number
  • Mention the task in a few words
  • Mention what types of files I changed
  • If it was a bug, mention what the bug was like before and after the changes
  • Describe the expected behaviour after the changes (Should it be the same?)
  • List any steps that need to be taken to check the changes, either in-browser or in the code
  • Note anything that should be ignored, for example a bug addressed in another branch
  • Include screenshots of the interface as necessary

This example is relatively simple, and you definitely don’t have to include everything in the above list if it is not necessary:

An example of a pull request with enough, but not too much, detail

Conclusion

Although I have provided some examples of where to include comments and some suggestions on what to avoid, there are no hard and fast rules about how to format comments in your code. The number of lines, words, or what information to include is up to you, or can be decided between you and your peers. As long as you keep the format consistent, it will keep things tidy and encourage other people working with the code to do the same.

There are many benefits associated with making comments a part of your development process. It’s good to get into the habit of including them where you see fit, especially when you have many people working on the same files. It also helps to consider other forms of documentation that are embedded in workflows – such as commit messages and pull requests – and not simply an external document of guidelines.

Do you follow any guidelines for commenting code? Or maybe you work in a company that has an different but effective kind of documentation?

  • http://www.adriansandu.com Adrian SANDU

    This is a great article about one of the most overlooked aspects of coding. I find myself guilty of many of the “sins” highlighted here. After all, “Who has time to write comments no one will read?” Then a new colleague comes in and looks flabbergasted at the code in front of them, scratching their head and asking themselves “What was that coder smoking when they wrote this and where can I get some to alleviate my headache?”

  • Yolanda

    Comments are very useful specially on code.. We don’t like writing comments it takes time, but love when we find on a piece of code hehe

  • http://exclusive-paper.com JanySmool

    Hi, I absolutly agree with you! I like more short and understanding comments! I think it is more beeter, if you need something or if you want something to know, DO IT RIGHT NOW!!!!
    Can you give some code explanation?

    • http://hey.georgie.nu/ Georgie

      Hi! I’ve actually written a brief description of the code above or below it, and explained why a comment might be needed. You don’t need to understand exactly what the code does, but the examples in this article are in CSS. Some of the code does not seem to follow good coding practices, but when comments are added, it can be seen that the author of the code wrote it that way for a reason (for example, using `!important` is not always recommended, but a comment can clarify why it is needed and what it may be overriding). If it’s not clear, let me know and I can explain further. :)

      • http://exclusive-paper.com JanySmool

        ))) I understand it))))thank you very much! Good day)

  • jacob

    Great article. I tend to document code when I can either pre-empt misunderstanding of code in the future, which could be either by me or someone else or when using controversial methods to solve a particular problem such as !important or if I have nested more than two or three levels deep and it starts to get confusing at first glance.

  • Ahmed Mahmoud

    I’m really very convinced that comments are bad and should be only used for unintuitive code

    for example:
    rather than=>
    //if user at top of page
    if(window.scrollY==0){

    }

    you include that comment in the code to be more readable in itself=>
    var isAtTop=window.scrollY==0;
    if(isAtTop){

    }

  • Ahmed Mahmoud

    I’m really very convinced that comments are bad and should be only used for unintuitive code

    for example:
    rather than=>
    //if user at top of page
    if(window.scrollY==0){

    }

    you include that comment in the code to be more readable in itself=>
    var isAtTop=window.scrollY==0;
    if(isAtTop){

    }

  • Tyler Benzing

    I personally NEVER use HTML comments. Now wait. 99% of the HTML I “write” is generated by PHP in conjunction with template files and such. Like you said, comments are for humans to better understand code. If I feel a comment is required I always put it inside PHP tags and use what is technically a PHP comment. The only person I want understanding my code is the developer, that’s the only person that needs to understand it. Forgoing static HTML comments adds a tad more security as it will make a potential malicious user’s job that much harder. There is no reason a front end user should see your comments unless it is simple meta data tucked away in the source such as a license or little jokes tucked away in the source for the curious to discover and have a nice chuckle.

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in Front-end, once a week, for free.