Format Your CSS

For years, I've always formatted my CSS in what I like to think of as the "traditional" manner. Each selector on one line, and each property indented one tab underneath:

  padding: 0 1.5em;
  margin: 0 auto;
  clear: both;
#content h2{
  font-size: 2em;
  height: 1.5em;
  margin-left: .75em;
  color: #000;
#content h2 a{
  font-weight: normal;
  float: left;
#content h3{
  font-size: 1.25em;
  line-height: 1.2em;

Pretty standard stuff. I'd break up sections with big comments, and that made it fairly easy to scan. While this format never caused and problems per se, and it was easy enough to implement, it never seemed completely ideal.

When I started working with Sprokets, the other front-end developer there was using one-line css declarations. This threw me for a loop for a while, but I slowly started liking it better and better.

The method I've finally settled on is based on the one-line approach, but with an extra twist: I indent the declarations based on it's place in the HTML document. For example, take the HTML for this simple page:

<div id="one">
<div id="two">
      <li>list item</li>

The CSS to access this code would be like this:

body{ properties; }
  #one{ properties; }
    #one p{ properties; }
  #two{ properties; }
    #two p{ properties; }
    #two ul{ properties; }
      #two ul li{ properties; }

This has worked very well for me so far, and I'm looking forward to trying out on some bigger projects. It allows me to scan through my CSS much more quickly, view comments more easily, and has the added benefit of helping me think through things like descendants and inheritance. Take a look at the CSS for this site to see it in action on a bigger scale.

This method, while new for me, is clearly not revolutionary. However, since I stumbled on it on my own, I thought some of you guys might benefit from it as I have. How do you format your CSS?