Casa de Lewis

14 December 2007

CSS Formatting

It’s common practice among good web designers to indent HTML. It’s easier to work on their code and it makes collaboration more efficient. As such, it’s amazing that CSS does not have a universal format. I’m currently aware of three popular formats when working with CSS. There appears to be more but many of them are a combination or a variant of these more widely used formats.

Single Line

body {font:76%/1.7 Verdana, Arial, Helvetica, sans-serif; background:#fff;}
p {font-size:1.5em;}

The single line rule set was a result of trying to optimize the CSS file to load faster. It might be an easy format to follow initially, but I find it hard to edit and troubleshoot the CSS. Some argue that it decreases vertical scrolling, but often at the expense of horizontal scrolling.

Indent

body {font:76%/1.7 Verdana, Arial, Helvetica, sans-serif; background:#fff;}
    p {font-size:1.5em;}

Indenting is similar to a tree view in that it reflects the structure of the HTML document. Each rule set is indented according to its place in the HTML, so the p element above is a direct child of the body element. It inherits the difficulty of single line CSS formatting, but it also makes it difficult to group selectors and utilize inheritance effectively.

Block

body {
    font:76%/1.7 Verdana, Arial, Helvetica, sans-serif;
    background:#fff;
    }

p {
    font-size:1.5em;
    }

The block method is an easy format to follow. Additionally, it’s easy to edit and troubleshoot the CSS. It does, however, increase the number of lines and subsequently vertical scrolling.

I have tried the various methods and choose to use the block method because I find it easy to write and edit. Like many web designers, I also use comments to differentiate parts of the document with a table of section comments at the beginning. This helps reduce the frustrations of vertical scrolling in large files.

The pros and cons of each method are quite subjective. Even as I write this I debate in my head the logic of my chosen format. It is probably for this reason that a universally accepted format has not won over all others.