CSS Formatter

So I created a CSS parser and formatter on the weekend; I think it’s kinda neat as it formats CSS “just the way I like it”.
Why would I do this, when there are so many CSS formatters available? Well, the aim of most formatters is to “optimise” the CSS
(ie: make it as small as possible), whereas the aim of my formatter is to make it as readable as possible.
How many times have you inherited a project, only to find the CSS is a giant mess?
Many of the available parsers don’t have the option to display each entry on a single line, and most don’t keep the comments!
And none of them allows you to format the CSS so that each entry is on a seperate line, and the entries are
preceeded by X tabs, as long as the entry itself is less than X tabs long (though you may be able to configure CSSTidy to do this?). Let me demonstrate, take this CSS:

/*      Spinner classes */
.narrowDark {
width: 16px;
height: 16px;
background: url( ../img/load_narrow_dark.gif ) no-repeat top left;
}

/*      Validation classes      */
.formField {
width: 1300px;/* The surrounding container for each form field */
clear: left;
}

.narrowDarkOLD { height: 16px; background: url( ../img/load_narrow_dark.gif ) no-repeat top left;       width: 16px; }

.formField {
height: 32px; }

/*      Menu    */
.paxMenuDropDown{ background-color: #eee; border-bottom: 1px solid #aaa }

.paxMenuDropDown li.active a:hover {
text-decoration:none;
background-color: #00f;
color: white; border: none;
}

What I want to do is turn it into this:

/*      Spinner classes */
.narrowDark,
.narrowDarkOLD                  { background: url( ../img/load_narrow_dark.gif ) no-repeat top left; height: 16px; width: 16px; }
/*      Validation classes      */
/* The surrounding container for each form field */
.formField                              { clear: left; height: 32px; width: 1300px; }
/*      Menu    */
.paxMenuDropDown                { background-color: #eee; border-bottom: 1px solid #aaa; }
.paxMenuDropDown li.active a:hover{ background-color: #00f; border: none; color: white; text-decoration: none; }

Here we have:

  1. One entry per line
  2. All the comments are intact, and moved outside the class definition (you probably don’t want to do this with IE6 hacks)
  3. Each property is sorted alphabetically
  4. Duplicate entries are merged (narrowDark and narrowDarkOLD)
  5. Repeated classes are consolidated (formField)
  6. Nicely indented at 6 tabs

Check out the CSS formatter here.

Leave a Reply