CSS Comments

Commenting out code in CSS is good practice and makes it easy to read. Comments can be used to explain what something does for your future-self or to make it quicker for other developers to understand what a particular piece of CSS code does.

 

In this tutorial we will learn how to use CSS comments and how to they can be used to build a structure to your CSS code.

 

Single-line CSS Comments

There are two ways to comment out single-lines in CSS. The first is to wrap the line in a /* */ (forward slash asterisk and a closing asterisk forward slash.)

 

/* everything on this line is commented out. */

 

The second approach is to use // (two forward slashes.) This is not an officially supported CSS feature and will throw a syntax error. However, if you are compiling your CSS using something like npm, it will treat these as normal comments and remove them in the build process so you can still use them depending on your workflow.

 

// the rest of the line is commented out.

 

note - most text editors will recognise // (two forward slashes) as a comment in .css/.scss files and style the text accordingly but not all.

 

Multi-line CSS Comments

To comment-out multiple lines or “blocks” of CSS, wrap the area in an opening /* and a closing */.

 

/*
main::after {
    content: '';
    clear: both;
}
*/

 

Documenting CSS Code with Comments

It is good practice to split your CSS code into different sections that cover the style of groups of elements and functionalities. You could have a layout section, buttons section, forms section, text color section, general section .etc. Each section of the code could start with a stylised CSS comment block containing the name of the section like this:

 

/* ============================================================================================== 

Layout classes

================================================================================================= */


.first {

    margin-left: 0;
}

.last {

    margin-right: 0;
}

 

When you come back to tweak the code it will be a lot easier to navigate around the CSS as you will know roughly where certain properties will be located.

 

Conclusion

You now know how to use CSS comments to notate your code in various different ways.

comment