1 minute read

In CSS files it is often necessary to structure code sections or explain what the written styles do. A great way to do that is through comments. A comment in CSS is an arbitrary text that is purely informative and does not affect the visual display of the site. Comments are not displayed on web pages in the browser.

Well-added comments can make your code more understandable. This is especially important for projects developed by large groups of people.

Syntax

The syntax of CSS comments is quite simple:

/* Any text */

Any text placed between /* and */ will be considered a comment. The text of the comment can be placed either on one or several lines.

Let's look at specific examples of how and when comments are used.

Single-line comments

Single-line comments, as you can guess from the name, occupy just one line. Take a closer look at the syntax of single-line comments:

p {
  color: blue; /* the color of the text paragraph is blue */
}

The visitors of your web page won't see this comment. With the aid of such notes, you will quickly remember what a certain code fragment is intended for – even if it's been a while since you last saw it. Comments can also serve as hints for other developers who will work with your code.

Multi-line comments

Comments that take up several lines are called multi-line. Consider their syntax:

/* The styles given
   to the paragraph
   with the text 
*/
p {
  color: blue;
  background-color: black;
}

Such comments are useful for explaining particularly complex pieces of code or temporarily disabling large code sections. Also, multi-line comments located at the beginning of a file are quite useful when you need to specify copyright information.

Disabling code fragments

Another important role of comments is temporarily disabling parts of code. Consider the following example:

/*
h1 {
  color: #33A1D9; 
  border-top: 2px solid;
  font-size: 3em;
}
*/

In this case, no styles will be applied to the h1 element, but we can make it "visible" to the browser again if we delete the comment symbols. This process is called uncommenting.

Temporary code disabling is a great strategy when it is difficult to locate an error. It's inconvenient to just remove the code because you may need to restore it, so commenting/uncommenting is a great solution.

Conclusion

Comments are really useful and hence you shouldn't neglect them. However, keep in mind that the more comments you add to your code, the bigger it gets, which affects the loading speed. Use comments wisely, and you will write the most understandable and readable code ever!

Oh, and by the way, on Hyperskill we often use comments to explain our examples to beginners!

738 learners liked this piece of theory. 8 didn't like it. What about you?
Report a typo