Comments
Six months from now someone opens the café's stylesheet and finds margin-top: -3px; on the price. Is it a hack for a font quirk, or a mistake? A single comment would have answered in one line. Comments are notes for humans that the browser ignores.
The rule
A CSS comment opens with
/*and closes with*/, and nothing else counts.
/* ---------- Menu ---------- */
.price {
color: green;
/* Nudge up so the price lines up with the dish name. */
margin-top: -3px;
}
/*
Old festival colour, kept until the owner decides:
.special { background-color: orange; }
*/A comment can sit on its own line, beside a declaration, or across many lines. Good uses:
- Explain why, not what.
color: green;explains itself; the reason for-3pxdoes not. - Label sections so a long file can be scanned.
- Switch code off temporarily while testing, by wrapping it in a comment.
Three rules that trip people up:
//is not a CSS comment. Browsers treat it as ordinary, invalid text, which breaks whatever comes next.- Comments do not nest. A comment ends at the first
*/it meets, even if you opened another/*inside it. - Comments ship to every visitor. Anyone can read them in the browser's developer tools, so never write passwords, private notes or internal URLs in them.
The shortcut
When you see a comment, find its first */. Everything from /* to that point is ignored; everything after it is CSS again, whether or not you meant it to be.
The attempt
/* .special { color: orange; /* festival */ } */
Drills
Answer fast — trust the rule.
Which of these is a valid CSS comment?
A stylesheet has the line // old colour directly above .price { color: green; }. What happens?
Which is the best comment to leave in the café's stylesheet?
Where does the comment in /* a /* b */ c */ end?
Remember
- CSS comments are
/* ... */only;//breaks the next rule. - Find the first
*/; that is where the comment ends. - Comment the why, and never put secrets in shipped CSS.
