Commenting your CSS code

Commenting your code: CSS Best Practices, Part 4

I’ve never been much for commenting my own code, until I realised how much it helps other developers understand my logic, approach and it shorten the time they spend on getting familiar with my projects.


CSS can be complex, especially when working on larger projects, and well-written comments can make it easier to maintain and modify your code over time.

Pros of commenting your code

Here are a few reasons why adding comments to your CSS is important:

  • Improve readability:
    Comments can help break up large chunks of code and make it easier to read and understand.
  • Document the purpose:
    Comments can explain what a section of code does, why it was written that way, and what the intended result is.
  • Facilitate collaboration:
    When working on a project with other developers, comments can help everyone understand the codebase.
  • Aid debugging:
    Comments can help identify the source of a problem and make it easier to fix bugs.

Best practices

When writing comments in your CSS code, it’s important to follow a few best practices to ensure that they are effective:

  1. Keep comments short and to the point.
  2. Write comments in plain language that is easy to understand. Even for non-devs.
  3. Explain why it was written that way and what the intended result is.
  4. Consider using headings and sections to group related code and comments together in large files.
  5. Be sure to update the comments as well. Outdated comments can be just as confusing as no comments at all.

Example on commenting your code

Here’s an example of a well-commented SCSS document according to my own standards.

A card used for an archive page

/* Card used for archive page
----------------------------- */
.card {
  // Layout
  border-radius: .625rem; 
  height: 100%; /* Use full height of the parent */
  background: var(--black-3); /* Set card bg color */

  // Image inside the card
  &__image {
    display: block; /* Display as an block element */
  }

  // Description after the image
  &__description {
    font-size: .825rem; /* Override default <p> size */
  }

  // Btns in the end of the card
  &__button {
    // Layout
    display: flex; /* Use flex to align the btns */
    flex-direction: row; /* Align btns side-by-side */
    justify-content: space-between; /* Space between start and end */
  }
}

Wrapping it up

In the end of the day, it’s up to your whether you want to comment your code. If you “lone wolf” a project, I can understand why you don’t want to comment your code, but it will be wise, if you’re having more than one front-end developer on a project.

More CSS best practices