Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
Web Dev + WordPress + Security

Obsessive CSS Code Formatting: Organization, Comments, and Signatures

One of my favorite aspects of producing clean, well-formatted CSS code is “meta-organizing” the document using comments. In CSS, comments are included in the stylesheet like so:

/* i am the walrus */

When used constructively, CSS comments serve to break down documents into distinct regions, provide key information about specific declarations, and bring order to even the most complex stylesheets. In my experience, a well-commented stylesheet improves efficiency and optimizes comprehension.

Working with CSS, you can add comments any way you want. There are many different ways to use CSS comments, and endless ways to get there. Let’s check out some practical and interesting ways to use comments, along with some creative ways of doing so.

Information about specific code

Surely the most common reason to use comments involves explaining various CSS rules. Especially helpful for unusual or unexpected code, explanatory comments generally are kept brief, look similar, and vary in location:

/* example border */
div#example_01 {
	border: thin solid red;
	}
div#example_02 {
	font-weight: bold;
	margin: 3em 0;
	_margin: 1em; /* IE6 hack */
	color: red;
	}

The obsessive-compulsive part of this type of commenting involves stripping down the explanation to a bare minimum. Instead of writing “some browsers get this, but not internet explorer”, I write, “non-IE only”. Additionally, I avoid using capital letters except when referring to acronyms. This helps maintain the flow of an otherwise entirely lowercase document, however I have also seen effective use of the crazy ALL CAPITAL LETTERS approach. And finally, only the opening (/*) and closing (*/) comment characters are included with the actual comment, along with a single space on either side. Taken together, these three techniques help keep these types of explanatory comments light, clean, and easy.

Organizing regions of code

An excellent way to stay organized when writing CSS is to group associated code blocks together in a way that is consistent and logical. For example, I generally break things down along the lines of:

  • global settings (resets, scrollbars, etc.)
  • primary layout structure (body, primary divs)
  • secondary layout structure (header, footer, sidebar)
  • tertiary layout structure (page regions, floats)
  • text-related treatments (headings, paragraphs, lists)
  • images, links, and other salient features (pre, code)
  • general styles (forms, tables, buttons, acronyms et al)
  • general classes (.clear, .center, .right, .left, etc.)
  • miscellaneous stuff and template code

Then, to organize such a stylesheet, each region would be clearly indicated with some sort of distinguishing comment. Although I tend to keep it simple with something along these lines:

/* === GLOBAL SETTINGS === */

..I have seen (and used) a variety of creative sectional comments:

/* GLOBAL SETTINGS
   ----------------------------- */


/* GLOBAL SETTINGS
   ============================= */


/* ==[ Global Settings ]== */


/* [[[ Global Settings ]]] */


/*** GLOBAL SETTINGS ***/


/* ===============
   GLOBAL SETTINGS 
   =============== */

..and the list goes on and on. Really, the only requirements for any CSS comment are the opening and closing characters — everything else is entirely up to you. In my stylesheets, I try to keep the sectional comments as obvious and recognizable as possible without interrupting the overall flow of the document. Generally, I like to include a few equality signs (“===”) and capitalize the entire comment to distinguish regional comments from the more specific variety targeting selectors, declarations, hacks, etc.

Navigating extensive stylesheets

For extensive or highly complex stylesheets, CSS comments can also be used to implement a “quick-jump” mechanism to facilitate easy navigation. By including a specific character within sectional comments, you provide a way to “jump” through the document by using your software’s inevitable “Find” feature. For example, with the following sectional comments dispersed throughout my stylesheet, it would be very easy to jump from one section to the next with a simple Find("=") command:

/* ===GLOBAL=== */
.
.
.
/* ===PRIMARY=== */
.
.
.
/* ===HEADER=== */
.
.
.
/* ===SIDEBAR=== */
.
.
.
/* ===FOOTER=== */
.
.
.

When doing this, it is important to choose a navigational character that is not used elsewhere in your CSS document. You may also want to use a CSS comment to include an organizational directory near the top of the document, thereby facilitating quick and easy stylesheet navigation:

/* CSS DIRECTORY
	1. =GLOBAL
	2. =PRIMARY
	3. =HEADER
	4. =SIDEBAR
	5. =FOOTER
*/

You could even include a key character within specific comments and hacks. Although I have never seen anyone use this technique, it is easy to imagine how something like this would be useful:

/* HACK DIRECTORY
	% box model hack
	$ targets safari
	& clearfix hack
	? targets IE 7
*/

..with the associated anchors also present within the comments themselves. The same line of thinking could be applied to nearly any important aspect of a stylesheet. Something like this would certainly help collaborators and clients understand and navigate the document.

Other remarkable uses for the humble comment

Okay, the article is getting rather long, so I will try to wrap it up. Here are some other great ways to use comments to improve the informational value of your stylesheets..

Timestamp and document information

An excellent way to stay organized on the team or network level, especially useful during periods of rapid collaboration or development. In addition to this example, check out the top several lines of just about any WordPress theme for an excellent “real-world” implementation.

/* DOCUMENT INFORMATION
	- Document: Jukebox Theme
	- Version:  1.2.3
	- Client:   Fonzi Winkler
	- Author:   M. Gibbonz   
*/

Color and font information

In an effort to streamline production and subsequent editing, I have adapted this excellent strategy for summarizing all of the colors and fonts used in the stylesheet. This practice has served me well on countless occasions.

/* COLORS
	- default body text  #ffffcc
	- subtitle h2 text   #ff9900
	- form input borders #cc9933
	- default p text     #f0f0f0
	- pre borders        #ffff99
*/

/* FONTS
	- default body text  Arial, Helvetica Neue, Helvetica, sans-serif
	- subtitle h2 text   Garamond, Hoefler Text, Times New Roman, Times, serif
	- form input text    Cambria, Georgia, Times, Times New Roman, Times, serif
	- default p text     Copperplate Light, Copperplate Gothic Light, serif
	- pre and code       Consolas, Lucida Console, Monaco, monospace
*/

Trademark signatures, quotes, slogans

Gotta have ‘em! Well, maybe not, but I certainly enjoy the opportunity to express myself creatively. For the past four or five years, my personal CSS signature thing has been this:

/* all your code are belong to poetry */

..which is placed at the end of every stylesheet. Although I cannot remember them now, over the years I have seen a good number of interesting signatures, including everything from song and movie quotes to personal thoughts and nonsense. If any of you have your own personal signature thing, I would love to hear it!

Time for some comments!

CSS comments are versatile and flexible enough to handle even the longest of fangs. Embellishing your stylesheets with informational and organizational comments is an excellent way to improve the overall quality of your CSS documents while enhancing usability and efficiency. Hopefully, this article will inspire some new ways for you to use comments in your next CSS adventure. Until then, tell us about your different CSS commenting techniques! New ideas, variations, improvements, styles — anything!

About the Author
Jeff Starr = Web Developer. Security Specialist. WordPress Buff.
Blackhole Pro: Trap bad bots in a virtual black hole.

11 responses to “Obsessive CSS Code Formatting: Organization, Comments, and Signatures”

  1. I use the built-in comments functionnality of TextMate, as shown on their screencast. It’s not as elegant as some of the variations you showcase 1, but it’s quite handy.

    Also, the idea of a hack directory, and the way you designed it is beautiful. The same goes for the document/color/fonts meta-information blocks; they are very clean, lovely.

    Note that I really like the following shape.

    /* ===============
          GLOBAL SETTINGS
          =============== */

    Thanks for making me discover it!

  2. You know, I’m ashamed to admit it, but as well as I know CSS, my stylesheet organizational skills just… suck. LOL. I mean, I literally code as I go, and just leave it there.

    Not only that, but there are so many developers who are so concerned with download times… they make it damned difficult to justify adding so much extra markup (as some of your examples are heavy on the characters.) I guess it’s just personal preference… so long as your CSS isn’t as sloppy as mine! LOL

  3. Perishable 2008/07/05 4:44 pm

    @Louis: Textmate is an awesome program, I’ll have to agree. Watching that screencast, I see that it can do much more than I ever imagined. Time for a fresh look into it! Also, thanks for the kind remarks about the comment styles in the article. I agree that the hack directory has a certain “hook” to it that just feels right. Once again, thanks for the great feedback! :)

  4. Perishable 2008/07/05 4:50 pm

    @Erika: download times are definitely important, and you caught me on something that I should have mentioned in the article: this sort of elaborate commenting and organization is intended primarily for development purposes. Once a clean, well-commented stylesheet is ready for public consumption, I highly recommend running it through some sort of CSS code optimizer. The optimized version is then served to visitors, saving them bandwidth and download times, while the development document serves as future reference for updates, maintenance, editing, and so on.

  5. Hey Jeff, you seem to be impressed by the screencast I linked, but it’s by far one of simplest task you would want to do with Textmate.

    I strongly recommend that you watch some of the other screencasts. You can also have a look at this Symfony framework video (404 link removed 2015/05/07).

    It has nothing to do with CSS formatting, but you’ll see how fast and efficient a Textmate user can be. In fact, I find it very hard to follow what the guy’s doing (this tutorial is bad pedagogy).

  6. Nikhil G. 2008/07/08 5:17 pm

    This may be out of context, but I am not able to post comments on your posts, e.g. APATHY. Huh?

  7. Nikhil G. 2008/07/08 5:18 pm

    Oh sorry, got it… OLD POSTS – NO COMMENTS.
    well, I had a small problem using apathy:

    “hey Perishable… I must say you made a fan by making this theme. :P

    anyways, I had a simple problem.
    can u check out how this theme works with Platinum SEO plugin, with rewrite title ON.

    When I tried, it showed “Featured| (blogtitle)” where FEATURED was the category i used for right side column.

    Thanks. I’m following up.
    Nikhil G.”

  8. SneakyWho_am_i 2008/09/26 2:28 pm

    Never included a table of contents, but I LOVE the idea!!

    Never included and never will include a font list, For the most part I am fine with the browser’s default decision. The main time I override it is for ascii art or code, where I need a monospace font.

    Signatures? In my CSS generally no. No timestamps, nothing. Ascii art? Yes. Jokes? Yes. Thanks to xyz for the clever hack? Yes.

    I am leaving more and more and more comments in PRODUCTION CSS now. I know it increases the download time by up to 1 second for dialup users on a bad day, and I know that I can theoretically lose views that way, but really I mostly code for the love of it and not for money, so I don’t care :D I’d rather that people could learn from what I’ve done… My stylesheets for profile pages on third party sites normally include verbose, foul-mouthed, long-winded complaints about layout tables and deprecated HTML attributes such as bgcolor.

    Important things are normally with an inline ====== horizontal rule ====== or the under-and-over style horizontal rules. Equals sign of course because it’s not part of the syntax and uses a lot of screen ink.

    /*
    Long comments are normally like this
    lorem ipsum etc
    blah blah
    */
    /* short comments have one interior space on either side. */

    All comments have a new line or space outside each delimiter, also, except in common cases where I was lazy, hit CTRL+D, and typed something else in.

    Back to this table of contents idea though.. I can’t use the “xyz hack” thing though.. I don’t use them for the most part now even when thy are valid CSS.But I can see how it could be useful in a big way for marking out elements with a specific purpose. Or for elements which are “high in red” or something.

  9. I know it increases the download time by up to 1 second for dialup users on a bad day, and I know that I can theoretically lose views that way, but really I mostly code for the love of it and not for money, so I don’t care

    — Hilarious! XD

  10. John Sinclair 2010/12/14 10:16 am

    Long ago I used to worry about comments and wasted space and download times … but not now. I have seen everything from nicely-indented, well-commented code, to code where the author removed every space, tab, and line-break. I prefer the former. It’s doubtful the difference between a 6k and an 11k stylesheet will cost you visitors. You may have more significant problems. Look at modern CMSs and blogware with their pounds and pounds of scripts and AJAX, boilerplates, and stylesheets with @imports (now there’s a cork). My comments are but a dish of olives at a banquet like that.

    Producing clean, easily maintained code is a developer’s job. Leaving behind nicely-indented, well-commented code is one part of demonstrating your competence. Efficient and attractive code is one way we show our respect for our craft and for our peers that practice it.

  11. Brilliant article!

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
SAC Pro: Unlimited chats.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.