Jump Menu : Content | Explore | Comments | Search | Home | Sitemap | Contact | Login | Access.

Obsessive CSS Code Formatting: Patterns and Trends

Call me strange, but I format each of my CSS rules according to the following pattern:

div#example element {
	margin: 5px 15px 5px 0;
	border: 1px solid #444;
	line-height: 1.5em;
	text-align: center;
	background: #222;
	font-size: 10px;
	display: block;
	padding: 5px;
	color: #888;
	float: left;
	}
div#another div.example element {
	border: 1px solid #444;
	margin: 7px 0 17px 0;
	letter-spacing: 1px;
	font-weight: bold;
	background: #222;
	font-size: 1.1em;
	cursor: pointer;
	display: block;
	padding: 3px;
	width: 308px;
	color: #888;
	clear: left;
	float: left;
	}
div#another div.example element {
	text-indent: -9999px;
	overflow: hidden;
	position: fixed;
	display: block;
	z-index: 9999;
	padding: 0px;
	margin: 0px;
	bottom: 0px;
	right: 0px;
	}

Notice how the right-hand edge of each block suggests a diagonal line? This is accomplished by placing the longest declaration at the top of the style block, then the second-longest, and so on until the shortest rule is finally placed at the bottom. I have been writing my CSS this way for several years now, and apply the principle to virtually all of my declaration blocks. Occasionally, other formatting patterns are seen. For example, layout divisions are frequently very similar in appearance due to similar rules with similar lengths:

div.subleft {
	width: 400px;
	float: left;
	clear: none;
	}
div.subright {
	width: 377px;
	float: right;
	clear: none;
	}
div.midleft {
	width: 177px;
	float: left;
	clear: none;
	}
div.midright {
	width: 200px;
	float: right;
	clear: none;
	}

Technically, I am still listing the rules in descending order according to length, but the similarity of the rule blocks presents a uniform aesthetic demonstrating clear thought and solid design. Further, the overall pattern consisting of short, uniformly sized blocks is easily recognizable as related to positioning and layout. Over time, familiarity with the different patterns facilitates efficient CSS navigation. Further, the highly elaborate, systematic ordering of CSS rules conveys a sense of completeness and closure to finished files. Also, as the degree of organization closely correlates with overall processing time, determining inherent code quality is greatly facilitated while scanning through previously designed stylesheets.

Related articles

About this article

This is article #526, posted by Perishable on Monday, April 07, 2008 @ 08:28am. Categorized as Presentation, and tagged with css, Presentation, streamline, tips. Updated on April 08, 2008. Visited 8782 times. 19 Responses »

BookmarkTrackbackCommentSubscribeExplore

« Perishable Press Theme Renovations Complete • Up • Three Unsolved WordPress Mysteries »


19 Responses

1 • April 7, 2008 at 9:34 am — Gabe says:

Dude, you’re right, that is totally obsessive. I bet it makes for a very easy on the eyes css file though. I’ll have to dig through mine and see if I notice any patterns.

2 • April 7, 2008 at 10:06 am — Perishable says:

Yes, it is.. Or at least, it sure seemed that way several years ago when I felt compelled to begin practicing it. These days, writing CSS code this way seems almost second nature — I don’t even think about it!

3 • April 8, 2008 at 3:50 am — Ryan Williams says:

I’d agree that this is a bit obsessive. ;) I have various OCD-like behaviours (never been officially diagnosed so I won’t call myself OCD), but with CSS formatting I practise a very simple, logical method: alphabetical ordering!

By arranging your rules alphabetically, you always know roughly in what part of the order your rule will be. The rule also won’t change position depending on the value, while with your system I imagine you’d have to re-order the rule if you changed, say, a margin: 1px; to a margin: 1px 1px 1px 0;.

You can see where I used my system here:

http://www.bramleycarrington.co.uk/css/stylesheet.css

From a totally biased perspective I’d say my technique is more useful (especially when sharing code with colleagues), while yours is pretty much completely for aesthetics. Still, everyone does things their own way. :)

4 • April 8, 2008 at 7:43 am — Perishable says:

Yes, that is one of the great things about CSS — it is so customizable that everybody can write it their own way. For me, the visual appearance of code (CSS, XHTML, PHP, etc.) on the page is immensely important. If the source code doesn’t look clean, well-structured, and highly scrutinized, then I usually either take the time to do it myself or refuse to use it at all. There is something very inspiring to me about well-formatted source code, CSS and otherwise. I think it’s great that people are getting into alphabetizing their code — it may in fact be far more useful, but it just doesn’t look as well-organized and logically written (to my obsessive eyes).

5 • April 8, 2008 at 9:18 am — Gabe says:

I guess I’m in the minority - I try to group my css logically. For example, I put all the base elements in one section, all elements with ID’s in a another section, and classes in another section. Within each section, I have subsections that grouped together based on the part(s) of the page(s) they are styling. For example, all of my left nav classes will be grouped together, etc. I really don’t mind what it ends up looking like. I’m a big fan of ‘ctrl+f’, that’ll take me to my destination much faster than any aesthetic organization. I do keep things clean in all my code (css or otherwise) by following strict indenting patterns and so forth because it helps me to know where I am in my code.

6 • April 8, 2008 at 10:46 am — Perishable says:

Hey, no disagreements here about such meta-organizational techniques. Keeping the selector blocks themselves well-organized and logically presented is an entirely different topic. Here, we are focusing in on CSS patterns and trends for code presentation within individual selector blocks. Even at this level, there are many different formatting techniques for code presentation, including my admittedly obsessive diagonal system, Ryan’s somewhat retentive alphabetical model, and many others as well. I guess the point is to actually have a system that works best for you, regardless of your preferred level of organizational focus, whether selectors, properties, values, declaration blocks, or whatever!

7 • April 9, 2008 at 6:34 am — Jordan Gray says:

Before I came here, I thought my code formatting habits were OCD, but now I see I’m just a pretender — bravo!

I follow a simple system. The first set of declarations establish the typography of the site, and deal with general text formatting. Next, each major section of the page (the header, main content, navigation, forms etc.) is clearly separated by whitespace, with selectors appearing in roughly the same order that the elements they correspond to will appear in the markup. Finally, I obsessively alphabetise and minimise each property declaration.

Oh, yes: I always put rules with only one property on a single line, i.e. “#some-ID { margin: 0; }”. It just looks right to me!

8 • April 9, 2008 at 9:54 am — Perishable says:

Another alphabetizer! I guess it’s more popular than I had first imagined, although, unless your selector blocks are like 50 lines thick, how useful is it really to alphabetize the declaration blocks? It seems like it would be just as easy to quickly scan the five or ten lines to find the target property rather than reading through the list alphabetically. On the other hand, alphabetizing declarations is solid, consistent method of keeping your code organized and consistent — and that is the whole point of this thread. As for minimizing CSS properties — I completely agree that it is good practice to do so. And for the single-property selector blocks, I have embraced that practice as well, as I find it helps bring a certain aesthetic texture to surrounding code blocks. By breaking up the repetition of typical selector blocks with a few well-placed one-liners, it is possible to bring additional character to a series of rules, almost like the role punctuation plays within a paragraph of text.

9 • April 9, 2008 at 4:59 pm — Jordan Gray says:

The useful thing about alphabetising — especially in large blocks, as you observed — is that you can very quickly verify whether or not a certain property has already been set. However, it probably has more to do with the perverse pleasure I derive from knowing that everything is in order!

I agree about the texture that one-liners bring; they break up the flow nicely, and it makes them feel more like brief asides, or perhaps the delicate touch of a master craftsman. (Pretentious, much?)

Of course, when it comes to clarity and grace, comments and whitespace are the peerless companions of any good CSS author. Any opinions on the age-old jihad concerning tabs vs. spaces?

10 • April 9, 2008 at 6:18 pm — Perishable says:

Ah yes, I see now how alphabetized declarations could assist in determining the presence (or absence) of a specific property/value pair. I will agree now that, technically, alphabetization is a more consistent and rigorous technique for ordering the contents of selector blocks. Still, I can’t quite get past the difference in appearance between any given alphabetized code block and one that has been organized specifically for presentational/aesthetic purposes. Call me a total CSS snob, but if the code doesn’t line up or demonstrate some form of clear pattern, it just looks unfinished and terribly sloppy! I love your second point and agree that we probably sound a bit pretentious discussing such minutia so relentlessly, but it’s difficult not to share the satisfaction of a well-placed, single-line selector block. As for the old “tabs-vs-spaces” jihad, it’s so over it hurts: (single) tabs all the way! ;)

11 • June 10, 2008 at 8:39 am — Andy Ford says:

aaaarrrrggghhhh!

It would drive me crazy to have to edit css like this! You’d never know ahead of time where to expect something.

I’d say, if in doubt: alphabetize.

Personally (and my approach would probably drive others just as mad!) I try to arrange properties based on how they affect the box model and document flow. Flawed at best, but I know that I’ll always have dimensions (height/width) near the top, and things like color and background at the bottom.

I’m not suggesting anyone follow my lead as it is pretty subjective guess-work. But I don’t think formatting based on the character width of the property/value makes sense or good practice. I’d advise alphabetical order to anyone just getting into css. (although I personally prefer to see ‘position’, ‘top’, ‘left’, ‘right’, ‘bottom’ etc paired together as it makes logical sense in my mind - so it’s always been hard for me to switch to alphabetical)

I don’t mean to be critical. My method is probably just as hard to follow as yours. And I’m glad you got this conversation started. It’s interesting to see how other people approach this thing with no clear guideline.

12 • June 10, 2008 at 9:56 am — Perishable says:

Hi Andy, thanks for sharing your thoughts! I think it’s hilarious that “you’d never know ahead of time where to expect something” — as if each code block contains hundreds of declaration blocks. You must be doing some serious CSS styling over there! I tend to take a minimalist approach to CSS: less is often more. I try to avoid bloated code and keep my styles lean, mean, and succinct as possible. Although several onerous elements (e.g., form elements, pre tags, etc.) frequently require a few extra properties, the number of declaration blocks for each selector generally remains quite low. Thus, if you have to use tons of code to style every selector, locating specific rules using my approach may indeed prove too difficult; however, for 99.99% of the CSS that I write, the obsessive method keeps things sharp, clean and beautiful.

13 • June 10, 2008 at 10:47 am — Andy Ford says:

@Perishable - Ryan Williams (comment #3) made a good point with his “margin: 1px; to a margin: 1px 1px 1px 0;.” example.

As I mentioned, I wouldn’t recommend my approach (order loosely and subjectively based on affect to box model), but I can generally and fairly reliably expect certain properties to be at the top or the bottom of any given declaration.

I also try to keep my css lean and mean, but sometimes you do end up with 13 properties as with your example “div#another div.example element”

It just doesn’t feel right (to me) to put arbitrary and transient formatting ahead of any form of logical or standardized structure be it box model, alphabet, or what have you.

Again, I’d recommend going the alphabet route for anyone wondering what to do. I keep thinking that someday I might finally switch to alphabetizing but I just can’t bring myself to do it. although it would be more in sync with FireBug which is *almost* reason enough.

I have to admit though, your approach is easy on the eyes

14 • June 10, 2008 at 10:22 pm — Perishable says:

All excellent points, Andy, and I follow your reasoning completely. I am with you — these are my personal, openly obsessive-compulsive coding habits and by no means do I recommend them to others. I do enjoy igniting conversation, however, and have always felt that unique styles warrant exclusive coverage.

Nonetheless, I still find it difficult to top a handful of lines for a majority of my selectors, but it does happen, and practicing consistent formatting definitely helps speed up the editing process. Whether that happens via my crazy method, your logical approach, alphabetization, or whatever, the point is to have a solid system in place for keeping your code clean, tight, and organized.

15 • June 16, 2008 at 1:50 am — carlnunes says:

I too was formatting my CSS like the above examples. I’m now making a conscience effort to develop a new style with as little code and typing as possible.

Did you know you don’t need a “;” on the last style in the brakets?

I just learned that!

16 • June 16, 2008 at 8:58 am — Perishable says:

Yes, that’s true — the closing semicolon is not required on the final property value for any given CSS code block, however, I have found it to be good practice to include it for all property values. Doing so helps to prevent mistakes when adding subsequent declarations, which happens frequently especially during development. I think certain CSS optimizers enable the removal of the last-value semicolon, which may be useful for “complete” stylesheets. Great comment, carlnunes — thank you!

Drop a comment

Trackbacks / Pingbacks

  1. CSSVault Blog » Blog Archive » CSS Code Formatting
  2. Links of Interest - CSS-Tricks
  3. DesignReadEnjoy75 at Daily.Phirebrush

Set CSS to lite theme
Set CSS to dark theme