Cách dùng comments trong CSS.
Bạn viết comments bên trong CSS stylesheets để briefly document (giải thích) code, cho bản thân hoặc team members.
Để viết comments trong CSS, dùng syntax/format sau:
/* This is a CSS comment */
Format /* */ là cách duy nhất viết comments trong CSS, do đó dùng cho cả single và multi-line comments.
/* This is a multi-line CSS comment. Also known as a block comment. */
Vài ví dụ dùng comment syntax để comment out CSS code bên trong 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; */ }
Trong thực tế, comments dùng cả để document code, và đôi khi comment out (vô hiệu hóa) certain style declarations khi testing.
Đừng nhầm CSS comments với JavaScript comments. Trong JavaScript /* */ (cùng format CSS) dùng cho multi-lines, single line comments dùng double forward slashes //.
- Single-line comments còn gọi inline comments.
- Multi-line comments còn gọi block comments.
Bạn có thể thấy projects dùng // cho single-line comments trong CSS code. Nếu nhìn kỹ hơn, bạn thấy họ dùng CSS Preprocessor, như Sass/SCSS, hoặc Less, cho phép single-line comments — như JavaScript. Trong vanilla (plain) CSS, unfortunately chỉ có /* */.
Nên viết comments trong CSS code không?
Như tôi giải thích trong how to comment HTML tutorial, developers disagree về topic này. Một số tin code nên explicit và self-explanatory.
Đối với tôi, topic không black and white. Không phải comment nào cũng bằng nhau. Bạn không nên dùng CSS stylesheets draft novel mới nhất, nhưng small, concise comments có thể make world of difference giúp beginners hoặc newcomers trong team hiểu code đang diễn ra gì.
Tôi chọn explicit hơn implicit bất kỳ ngày nào.
Đừng lo comments占用太多space伤害page load. Comments, hoặc text nói chung, là điều cuối cùng nên lo khi improve performance/page loading speeds. Ngoài ra, có tools remove comments during post-processing.