CSS Comments
By Flavio Copes
Learn how to write comments in CSS with the C-style /* ... */ block syntax, why there are no inline // comments, and how // silently breaks the next rule.
You write comments in CSS using the /* this is a comment */ C-style (or JavaScript-style, if you prefer) syntax. It works in a CSS file, and in the style tag in the page header.
This is a multiline comment. Until you add the closing */ token, all the lines found after the opening one are commented.
Example:
#name { display: block; } /* Nice rule! */
/* #name { display: block; } */
#name {
display: block; /*
color: red;
*/
}
What are comments useful for?
You can label the sections of a long stylesheet, so you can find things faster when you scroll:
/* ---------- header ---------- */
.site-header {
background: white;
}
You can leave a note explaining why a strange rule exists, so your future self doesn’t remove it.
And you can temporarily disable a declaration while debugging, without deleting it:
.site-header {
/* position: sticky; */
top: 0;
}
Wrap the line in a comment, reload the page, and see what changes. Then restore it by removing the comment markers.
Comments can’t be nested
Be careful when you comment out a block of CSS that already contains a comment. The comment ends at the first */ the parser finds:
/* disabled: .site-header { background: white; /* why? */ }
Here the comment closes right after why?. The leftover } is a syntax error, and it can break the rules that come after it.
The fix: remove the inner comment before wrapping the block, or comment out the lines one by one.
What about // comments?
CSS does not have inline comments, like // in C or JavaScript.
Pay attention though - if you add // before a rule, the rule will not be applied, looking like the comment worked. In reality, CSS detected a syntax error and due to how it works it ignored the line with the error, and went straight to the next line.
Knowing this approach lets you purposefully write inline comments, although you have to be careful because you can’t add random text like you can in a block comment.
For example:
// Nice rule!
#name { display: block; }
In this case, due to how CSS works, the #name rule is actually commented out. You can find more details here if you find this interesting. To avoid shooting yourself in the foot, just avoid using inline comments and rely on block comments.
Related posts about css: