How Good Are Your HTML and CSS Comments?

Share this article

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?

Frequently Asked Questions (FAQs) about HTML and CSS Comments

What is the importance of using comments in HTML and CSS?

Comments in HTML and CSS are crucial for several reasons. Firstly, they help in understanding the code structure and functionality, especially when working in a team or revisiting your code after a long time. Secondly, they can be used to temporarily disable certain parts of your code during debugging. Lastly, comments can provide useful information or instructions to anyone reading the code.

How can I comment out code in HTML and CSS?

In HTML, you can comment out code by wrapping it between . For example, . In CSS, comments are made by wrapping the text between /* and /. For example, / This is a comment */.

Can comments affect the performance of my website?

No, comments do not affect the performance of your website. They are ignored by the browser during the rendering process. However, excessive comments can increase the file size, which may slightly affect the loading time.

What are some best practices for writing comments in HTML and CSS?

Some best practices for writing comments include being concise yet descriptive, commenting on complex or important sections of code, and avoiding unnecessary or redundant comments. It’s also a good practice to regularly update your comments to reflect changes in your code.

Can I use comments to hide code from certain browsers?

Yes, comments can be used to hide code from certain browsers. This technique, known as conditional comments, is often used to provide different styles or scripts for different versions of Internet Explorer.

How can I use comments for debugging?

Comments can be used for debugging by temporarily disabling certain parts of your code. This can help you isolate and identify problematic sections of your code.

Can I nest comments in HTML and CSS?

In HTML, you cannot nest comments. Attempting to do so may cause unexpected results. In CSS, you can nest comments, but it’s generally not recommended as it can make your code harder to read and understand.

What is the difference between single-line and multi-line comments?

Single-line comments are used for short explanations or annotations, while multi-line comments are used for longer descriptions or blocks of code. In HTML, all comments are technically multi-line. In CSS, single-line comments start with // and end at the end of the line, while multi-line comments start with /* and end with */.

Can I use special characters in my comments?

Yes, you can use special characters in your comments. However, in HTML, you should avoid using the characters “–” within your comments as they can cause the comment to end prematurely.

How can I use comments to improve the readability of my code?

Comments can improve the readability of your code by providing explanations and annotations. They can also be used to separate different sections of your code, making it easier to navigate. However, it’s important to strike a balance between commenting and over-commenting. Too many comments can make your code cluttered and harder to read.

Georgie LuhurGeorgie Luhur
View Author

Georgie is a front-end web developer at Campaign Monitor and a concert photographer for Casual Band Blogger. She likes Japanese food, painting her nails, pop rock music, and salted caramel everything. You will always find her looking for new teas.

commentingcss commentslearn-advanced-csspatrickc
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week