Techstacker
Light ModeDark ModeReset dark mode. Falls back to OS dark mode setting.

Pages

No results for 'undefined'

Blog Posts

No results for 'undefined'
Powered by Algolia

How to Comment CSS Code

Nov 4, 20192 min readCSSViews:

How to use comments in CSS.

You write comments inside CSS stylesheets to briefly document (explain) the code, either for yourself or for members of your team.

To write comments in CSS we use the following syntax/format:

/* This is a CSS comment */

The /* */ format is the only way to write comments in CSS, therefore it’s used for both single and multi-line comments.

/* 
   This is a 
   multi-line 
   CSS comment.
   Also known as a block comment.
*/

A couple of examples using comment syntax to comment out CSS code inside rule-sets:

  .box {
    background-color: #000;
    padding: 1.5rem;
    /* border-radius: 4px; */ 
  }
  .box {
    background-color: #000;
    padding: 1.5rem; /*
    border-radius: 4px; 
    box-shadow: 5px 10px #888888;
    */
  }

In practice, comments are used both to document code, and to sometimes comment out (deactivate) certain style declarations while testing.

Don’t confuse CSS comments with JavaScript comments. In JavaScript /* */ (same format as CSS) is used for multi-lines, while single line comments use double forward slashes //.

  • Single-line comments are also called inline comments.
  • Multi-line comments are also called block comments.

You might have seen some projects where they’re using // for single-line comments in their CSS code. If you look a little closer you’ll see that they’re using a CSS Preprocessor, like Sass/SCSS, or Less, which do allow single-line comments — just like JavaScript. In vanilla (plain) CSS, unfortunately we only have /* */

Should you write comments in your CSS code?

Like I explained in the how to comment HTML tutorial, developers disagree about this topic. Some believe that your code should be explicit and self-explanatory.

For me, the topic is not black and white. Not all comments are written equal. You shouldn’t use your CSS stylesheets to draft your latest novel, but small, concise comments can make a world of difference to help beginners or newcomers in a team understand what’s going on in your code.

I’ll take explicit over implicit any day.

Don’t worry about your comments taking up too much space and hurting your page load. Comments, or text, in general, is the last thing you should worry about when it comes to improving performance/page loading speeds. Besides, there are tools that can remove comments during post-processing.