Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Thursday, January 31, 2013

How Should You Format Your CSS?

Does it matter how you format and organize your css? Are there compelling reasons to writing single line css as opposed to multi-line css? Or in the end is it all a matter of personal choice?

I thought it was a conversation worthy of a post and also fit with the recent talk here about different ways to write css.
Instructions for exam format

Why CSS Formatting is Important

If the only reader of our css was a browser, then how the code was formatted wouldn’t matter. We’d all minify our css and be done with it. You and I might not be able to read the minified code, but browsers would be fine with it. In fact we probably should be minifying our production code at this point.
However, we do need to read our css and likely have others read it as well. Given that human beings will be reading your css the basic goals of formatting should be.
  • Readability
  • Maintainability
While we should write code that we can both read and maintain first and foremost, we can’t ignore that other people will likely read our code at some point. We should also think of our future selves. I’m sure you’ve written css that seemed clear when you wrote, but not so much several months later when you needed to modify it. I know I have.
CSS with multi-line formatting

Different Styles of CSS Formatting

There are a variety of ways to format css, each with some pros and cons. Ultimately I don’t think there’s a single way css needs to be formatted as we all have different preferences. Still we should be aware of the pros and cons of the choices we make.
One of the first formatting choices you’ll make is to write single line or multi-line css.
Single line css — makes it easier to find selectors across a document, however it’s usually harder to find a specific property within a selector. This wasn’t so much an issue in the past when we didn’t use too many properties, but as css has given us more to play with and vendor prefixes have entered the picture, our list of properties has grown.
1
2
3
4
5
#globalnav { }
#globalnav a { }
#globalnav a:hover { }
#globalnav li ul { }
#globalnav li ul a { }
Having all your selectors grouped together like above, each on a single line makes it easy to scan a file and find blocks of code that style a particular design element, in this case a global navigation bar. It would be quick to zero in on #globalnav a for example, even in a large document.
However once you start adding in some properties it’s not so clean and nice.
1
#globalnav {list-style: none; font-family: 'Helvetica'; border-radius: 7px; background: #777; overflow: hidden; -webkit-box-shadow: 2px 2px 10px #ccc; box-shadow: 2px 2px 10px #ccc; -moz-box-shadow: 2px 2px 10px #ccc; -o-box-shadow: 2px 2px 10px #ccc; padding: 0; background-image: -webkit-linear-gradient(#777, #555); background-image: -moz-linear-gradient(#777, #555); background-image: -o-linear-gradient(#777, #555); }
That’s one long line of css. Not too hard to find the #globalnav selector, but not too easy to find specific properties within.
Multiple line css — is the opposite. It’s easier to find properties within a selector, since each get’s it’s own line, however it’s usually harder to find a specific selector as more scrolling up and down is needed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#globalnav {
  list-style: none;
  font-family: 'Helvetica';
  border-radius: 7px;
  background: #777;
  overflow: hidden;
  box-shadow: 2px 2px 10px #ccc;
  -webkit-box-shadow: 2px 2px 10px #ccc;
  -moz-box-shadow: 2px 2px 10px #ccc;
  -o-box-shadow: 2px 2px 10px #ccc;
  padding: 0;
  background-image: -webkit-linear-gradient(#777, #555);
  background-image: -moz-linear-gradient(#777, #555);
  background-image: -o-linear-gradient(#777, #555);
}
Much easier to read the properties of #globalnav when written on multiple lines, isn’t it? Of course the other selectors around it have probably been pushed off the screen and so finding #globalnav a might not be as quick and easy.
Drawing of a school of fish organized into a single larger fish

Organizing and Improving CSS Formatting

You probably have a strong preference for one of the two styles of formatting above. In either case there are things you can do to improve readability and maintainability.
Ordering css properties — With either single or multiple lines we can be consistent with the order we write properties. Jonathon Snook suggested an order of:
  • box properties
  • border properties
  • background properties
  • text properties
  • other properties
Seems like a good idea even if you prefer a different order of property groups. In the multi-line case we could leave a blank line between groups and in the single line case we might compromise and start each group on a new line.
Tabs between properties — With single line css some people have attempted to use whitespace through tabs to improve readability.
Unfortunately properties don’t necessarily line up in columns well since they aren’t the same from one selector to the next. I’ve tried this a few times and outside of special cases have never found it to work well.
Indentation of nested selectors — WIth multi-line css some will use indentation to show selector relationships and structure. The selectors aren’t technically nested, but use whitespace to make them appear that way.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#globalnav {
  property: value;
  property: value;
}

  #globalnav a {
    property: value;  
    property: value;  
  }

    #globalnav a:hover {
      property: value;  
      property: value;  
    }
While showing the relationships is appealing, I haven’t had much luck with this style of formatting either as I find the “nested” selectors get lost and appear to be properties of the main selector at first glance. It might just be case of needing to get used to it, though.

Higher Level Improvements

There are some things we can do at a higher level to improve css readability and maintainability regardless of your choices with anything above.
Sectioning and organizing files — At the very least we should be organizing our css files in some way. All your global navigation styles in one section and your footer styles in another. Perhaps you’d prefer all typographic styles in one location and all color styles in another.
It’s not always clear how best to organize sections though, which is what led me into this recent look at css.
Taking things a little further you might choose to use a single css file or multiple css files. Multiple files might be cleaner, but require additional http requests.
Comments — You certainly want to use comments for for major sections and probably for specific properties to remind yourself why you chose a particular value. If you still use the occasional hack for one browser or another a comment is likely necessary.
Comments need to strike a balance. Commenting everything is just as bad as commenting nothing,
Better naming of classes and ids — This is always a good idea. Good names need little explanation, though it’s not always obvious how to best name classes and ids.
Abstract art with the word Formatting

My CSS Formatting Practice

You might be curious about my formatting practices. I’m ashamed to admit they haven’t changed much over the years. I still format based on habits established long ago.
Early on I made the decision to write single line css for a couple of reasons.
  • Less whitespace to keep file sizes smaller. This is in the days before minification.
  • Ease of finding selectors. I used less properties in the past
Since then I’ve experimented here and there with refining things, but nothing has stuck. When presenting examples here I do write multi-line css, since I agree it’s much easier to read for short blocks of css.
I’d like to tell you I’ve been good at commenting my code, but I can only say I’ve been good on an inconsistent level. I generally keep files organized, but the comments don’t always find their way in. I’m happy to say I’m getting better at being more consistent.
I’ve typically organized css styles in a top down approach to mimic how the html is structured, as I suspect most of you do. There are sections for base styles and common classes, but otherwise my css is typically organized as follows:
1
2
3
4
5
6
7
8
9
10
11
#header { }
blocks of styles relating to the header

#main-content { }
blocks of styles relating to the main content

#sidebar { }
blocks of styles relating to the sidebar

#footer { }
blocks of styles relating to the footer
I’m been consistent in regards to naming classes and ids, though I’ve changed my convention over the years.
CSS

Closing Thoughts

I think how you format your css is mostly a matter of personal choice. If you’re working in a team it makes sense to agree upon a consistent system, but when working for yourself it’s hard to argue against writing it your own way. You aren’t going to know the preferences of those who later read your code so why try to predict it.
Your main choice will be single or multiple lines. After that you should try to refine your approach to make things more readable and maintainable. You can organize files and properties, try tabbed or nested indentation, or anything else you think will make your css clearer.
I have a feeling my current preference is going to change once I explore css preprocessors. I think it’ll be enough of a difference to shake me out of long ingrained habits. I assume at that point I’ll write multi-line and nested preprocessed css and output minified css for production.
However, viewing source code was and is a great way to learn to code and I want to provide that resource here. Whether that means not minifying or whether it means providing a non-minified version for download is something I’ll decide when I get there.
How about you. Do you have a formatting preference? Do you write single line or multi-line css? What additional refinements do you make to improve readability and maintenance?

No comments:

Post a Comment