CSS commenting strategy

December 12, 2011

After a few recent projects, I’ve realized a good commenting strategy is necessary in CSS (and any other language really). After running into problems of our own with mysterious or vague code, I figure I’ll share my general set of quick and flexible guidelines for commenting in CSS.

Here’s what my typical (non-LESS) CSS file looks like:

To start, each file should include a repeated name and short description. While the name here can be the same as the filename (as I’ve indicated), combined with the description, it can help you add clarity for other designers. For instance, if you compile multiple CSS files, these comments can guide you in reading the final file.

Moving along, every major component is broken down into its own section. Not shown above is that each section has two to three lines after it to space things out. Subsections of that component have their own sub headings as well to further break things apart for readability and documentation.

Really though, the last two types of comments are the most important to me. The others are honestly more of a formality and sanity check as searching is just as fast in most cases. These last two are what keep you and your coworkers happy. Take this example of a typical comment and snippet of CSS:

The comment adds no value to anyone because it doesn’t tell you why this code is there in the first place. Here’s what might work a bit better:

While not the greatest example in the world, it illustrates the point. The last type of commenting, inline notes, works well with this as it provides line-by-line justification for properties. Even though some folks might know \9 is an Internet Explorer hack, not everyone does and comments don’t hurt anyone.

CSS, and any code for that matter, is much more legible and maintainable with the right comments. The why’s and inline context matter most for justifying why blocks of code appear in your files in the first place. Most importantly, commenting makes or breaks a team’s ability to quickly execute and update projects. Figure out your own solution, carry it through, and watch your projects become easier to maintain.