Let’s move beyond simply linting our code, and delve into creating a visual outline of our CSS. Anyone who writes code, anything from simple UI shifts through complex exotic joins, inherits a responsibility to write reasonable code. Good code solves a problem or answers a question; well-written code lives on, open and accessible to future developers.
Before we begin, let me say that the delivered stylesheet should be minified and free of excess spaces, tabs, semicolons and lengths of 0px instead of “0″, using tools like the YUI compressor or the CSS Drive Online CSS Compression Utility.
I have read and been part of many discussions about the format of a CSS document. I happen to prefer to keep my declarations line-separated, alphabetized within contextually appropriate groups. I also like to keep the entire ruleset on one line, unless the ruleset is too long (I know, that’s subjective, but it is my blog).
Recently, though, I’ve had to work on some interesting and complex designs. As the DOM depth grew, I found myself getting lost in my own HTML. The solution, for me, was a simple one, both easy to implement and easy to back out of (especially when using the tools listed above).
My CSS formatting rules were category based:
- Reset CSS, if necessary/desired (note, I don’t always use a full reset library)
- HTML declarations
- ID rules
- class rules
Beyond that, I found my formatting rules lacking. Last-in mental flow within category left me lost and confused. To buttress my existing formatting rules, I adopted a visual outline in my stylesheet that matched the indent rules of my HTML. For example, the following HTML:
Would be supported by this CSS:
There’s nothing new or magical here. In fact, this isn’t even a very pretty implementation of a flyout menu. The point here, though, is that my CSS has been formatted to mimic the indentation and format of the HTML. Clearly, “li” is a child of “ul” is a child of “#nav” and so on. As your style sheet grows, you’ll be glad you took the extra steps to maintain a mock of your HTML formatting.
Don’t forget – the final step before publishing to production should, at the very least, be minification!