Obsessive CSS Code Formatting: Patterns and Trends

Posted on April 7, 2008 in Presentation by

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

26 Responses

  1. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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. 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. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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. [ Gravatar Icon ] 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!

  17. [ Gravatar Icon ] Lie says:

    I think I’m the most minority here.

    Am I the only one here that orders CSS in most dangerous to most subtle order? My CSS, at first glance, would look messy and unordered, but if you looked closely enough, you’ll see a pattern: CSSs that defines abstract positioning behaviors is positioned on the top (display, float, etc), then concrete positioning (width, left), then text positioning (padding, margin), and lastly anything related with colors (which if changed would affect the overall layout the least)

    Even among those general layout, there are subtler ordering, such as margin first then padding since margin is more outside, background-color first then color, etc… it’s very complex but most logical to me…

    I order it this way since I think properties that could affect the overall layout the most is more important and should be placed higher, while things like coloring are subtler and is less likely to affect overall layout.

  18. [ Gravatar Icon ] Jeff Starr says:

    Hi Lie, I think your strategy is great, and have taken a similar approach on past designs. Especially when it comes to selectors containing a lot of individual declarations, ordering the rules according to functionality seems like an excellent approach. The key here is to know enough about CSS to actually have a strategy, and then staying consistent with and continually improving upon it. Thanks for sharing! :)

  19. …er….that is a bit crazy. My GF says that she counts the letters of every word she says in her head before she says them…this sounds like a similar thing!!

    Just one question - Do you think using wierd OCD CSS patterns has any impact on SEO etc?

  20. No. As far as I’m aware CSS in general has no factor on SEO, although I guess Google could theoretically put significantly less weight on things with display: none and stuff like that.

    That’s another discussion really, though!

  21. I love that the comment form here is consistent across platforms and browsers even though it is so crazy. It’s great. OK on topic:

    - Don’t look at my linked website as an example, it simply does not apply.

    I’m another with what you would probably consider really bad CSS then. I try to keep one block per line.. I don’t use positioning at all, I lean heavily on paint order and the “display” property to lay out my stuff. My colours for most things are set within four or five blocks, so I don’t worry about them for the rest of the file except for headers, “panels” and such.

    I have a small screen at the moment too, and don’t like scrolling down a lot. One word per line is not very fun to look at when you can only fit a handful of lines on a screen.

    The lines I am breaking off at about 70 columns. Some things with LOTS of properties (especially big ones) I will sometimes lay out vertically for readability - a big thick paragraph I can not deal with in CSS.

    The blocks are layed out by the specificity of the selectors. Very nonspecific selectors (wildcard, body, html) and css resets go at the top. Below that are element and then class selectors. Below that are ID selectors, if any. This is partly to prevent rules from being overridden accidentally, and partly because it means I have a solid base at one end of the file and picky garbage at the bottom.

    Yeah, the order of the properties has no concrete rule, so it must look disorderly. I like to keep color and background together. I like to keep outline and border together. I like to keep position, display, width, height, margin, and padding together.
    But these rules about the orders they come in are not enforced. I’m too busy paying attention to white space, and writing comments.

    I have no tab spacing in my css.
    An opening brace must go on the same line as the selector, and have one space to its left, and one space or new line to the right.
    A closing brace may have a new line or a single space to the left, and a new line to the right.

    Commas must have no whitespace to the left, one space or new line to the right. If it’s a new line then the first character on the new line must be part of a selector. Selectors are never indented.

    Each colon (:) must have a property name and no space to the left and one white space to the right. Each semicolon must have a value to the left and a single space or new line to the right.

    Anything in brackets must be quoted. Otherwise some syntax highlighters pick up the dot notation and highlight parts of the url as classes - which just looks stupid.
    No spaces are required inside round brackets except where the round brackets contain commas or multiple values (such as rgb or rgba colours), and then the spaces must be used only to separate each value in the usual way.

    Comments can be inserted absolutely anywhere. This is a source of error at times, and clutters my code. It is partly due to having CTRL+D mapped to “comment out whatever I’m looking at right now”.

    Finally, the final semicolon in each block MUST be present. I consider it a linting issue. I like to sometimes cut some properties out of block x and paste them into block y (shuffling colours around etc) and if my code isn’t of reasonably strict syntax (including the trailing semicolon), I can and do create bugs.

    And that’s my life story.

  22. [ Gravatar Icon ] Jeff Starr says:

    Incredible comment there, SneakyWho_am_i — perhaps the longest comment here at Perishable Press..(?) I don’t know, but a couple of things caught my attention.

    First of all, be careful when using quotes within all parentheses (what you refer to as “brackets”). If I remember correctly, there are certain CSS directives and declarations that behave differently across browsers depending on whether or not the parenthetical content has been quoted. I think this applies mostly to the @media and @import directives on older browsers, but other configurations and/or declarations could result in unexpected or otherwise unexplainable behavior.

    Secondly, I am curious as to the meaning of “linting” as used in your comment. I understand the intended meaning of the sentence based on the subsequent context of the paragraph, but I am unfamiliar with the term and its usage. How would you define it?

  23. Ah, yes, good point about the quotes in parentheses! Thank you! :)

    Sorry for just saying “linting”, what’s really bad is it’s a made up word basically! I meant to refer to the use of lint to find bugs in your C before you compile it. I’m not a C coder and if I understand correctly it has kind of gone out of fashion as the compiler itself now complains about a lot of things on its own.

    In javascript I often use a tool called “jslint” which helps you to “lint” your code and spot unknown bugs.

    PHP has a built-in lint tool.
    If you run the command line php with the “-l” (lowercase “L”, for “Lint”) switch, it will check the syntax of the file passed to it.

    If you set your error reporting mode to “E_ALL | E_STRICT” (in php6 will just be E_ALL) it will tell you off for measuring undeclared variables and it will tell you off for making dangerous or deprecated function calls.

    I enjoy checking my scripts now against whatever lint tool or validator I can find. Most of the time my work is still pretty bad, but at least I’m not surprised by bugs in my bad work very often.

    A good lint tool I think really won’t just validate your code, it should also warn about bad or dangerous style. This makes jslint a reasonable example of a lint tool anybody can use.

    http://www.jslint.com/

    I should warn that JSLint is very cruel, and an experienced coder will deliberately do shorthand things that she warns against, including:
    - test undeclared variables
    - declare functions after the code that uses them (especially nested functions)
    - assign-and-test (single equals sign in parentheses)
    - use prefix or postfix increment operator

    Information about why it can be a bad thing can be found here:
    http://www.howtocreate.co.uk/strictJSFirefox.html

    But regardless of whether some judgements are wrong or right, I definitely find it useful to check that I haven’t got error-causing syntax or executable typos in my code.

    A long explanation with no css-based examples for one word in a comment about something to do with css!

  24. [ Gravatar Icon ] Jeff Starr says:

    Incredibly useful response, thank you very much! I had suspected that “linting” had something to do with checking Perl code, but had not heard it used in the context of CSS. Now that you mention JSLint, everything makes sense. I am familiar with JSLint as a JavaScript validator (although I don’t use it personally), and see now how “lint” has become somewhat of a general term for checking or validating the syntactical accuracy of various types of code. For CSS code, it is generally easy to spot errors by observing discrepancies in the syntax highlighting provided by Coda, Dreamweaver, or whatever. Thanks again for taking the time to explain this!

  25. [ Gravatar Icon ] Jamy Golden says:

    I’m a bit late to this whole discussion! But I alphabetize, except I will always add ‘position, left, top’ at the end. However z-index trumps that, and vendor specific CSS trumps all. Sometimes I create an extra selector just to add the vendor specific CSS.
    Also, every property has it’s own line and it is never broken - This is why I have to have it in alphabetical order.

    I quite like your good looking CSS Jeff :) When I look at it I don’t feel like deleting it all just to see some white space lol.

  26. The only pattern in mine is alphabetical ordering, I just love doing my CSS like that. ^_^

    In terms of block patterns, I usually do top to bottom (example being wrapper > header > sidebar > footer > etc.)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Please use basic markup. Wrap code with <code> tags!