Obsessive CSS Code Formatting: Patterns and Trends
Call me strange, but I format each of my CSS rules according to the following structure/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.
28 responses to “Obsessive CSS Code Formatting: Patterns and Trends”
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.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.
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!
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!
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.
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! :)
…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?
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!
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.
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?
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!
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!