TLDR: watch the YouTube video instead
When it comes to writing clean and maintainable CSS code, comments play a crucial role in improving readability, collaboration, and long-term code management. By providing context, explanations, and reminders, comments help both current and future developers understand the purpose and functionality of the code. CSS comments can serve as notes for developers and have no impact on the appearance or behavior of the webpage.
Let’s learn the syntax for CSS comments and where you can and cannot put comments in your stylesheets.
CSS Comment Syntax
The syntax for writing comments in CSS is the same for both single-line and multi-li e comments. They are enclosed between a forward slash and an asterisk (/*
) to start the comment block and an asterisk and a forward slash (*/
) to end the comment block.
Single-line example:
.selector {
property: value; /* This is a single-line comment */
}
Multi-line example:
/* This is a multi-line comment
spanning multiple lines of code */
.selector {
/* Commented out code
property: value;
*/
}
You can learn more about CSS in the book “HTML and CSS: Design and Build Websites” by Jon Duckett.
Where can you put CSS comments
The following code sample shows all the valid ways to write comments in CSS, like:
- On the line before the styles
- On the line after the styles
- Same line, before the declaration
- Same line, after the declaration
- Same line, in the middle of the declaration
/* On the line before the styles */
p {
color: red; /* Same line, after the declaration */
/* Same line, before the declaration */ display: flex;
display: /* Same line, in the middle of the declaration */ flex;
}
/* On the line after the styles */
Conclusion
Well-crafted comments in CSS code can significantly enhance code readability, collaboration, and maintainability. By using single-line and multi-line comments effectively, you can provide essential context, explanations, and reminders to yourself and fellow developers.