Auto formatting CSS code with JavaScript

The guys from Webstandards Blog have written a guide to front-end developers on writing beautiful and efficient code. Based on their idea, I write the following code with Krause. It orders and formats CSS code with the rules designed by them.

Some text editor allows you to write plugins using Javascript. This code can be useful in that context.

Notice that only properties defined in props array are ordered. Other properties are placed at the end of the rule. You can add more properties to props as you want.

// The original CSS rule.
var css = 'body#teste #limites ul { clear: both; margin: 0; '
    + 'font: 12px Arial, sans-serif; width: 100%; left: 0; }';

var props = [ 'position', 'top', 'left', 'float', 'clear',
    'display', 'width', 'height', 'margin', 'padding', 'border',
    'background', 'font', 'line-height', 'text', 'color' ];

var parts = css.match(/^\s*([^\{]+?)\s*\{([^\}]+)\}.*$/);

var selector = parts[1];
var myprops = parts[2].split(';');

var newprops = [];
var last = props.length;

for (var i = 0, s = myprops.length; i < s; i++) {
  var p = myprops[i].match(/^\s*([^:]*)\s*:/i);
  if (p) {
    p = p[1];
    boolean o = false;
    for (var j = 0, t = props.length; j < t; j++) {
      if (p == props[j]) {
        newprops[j] = myprops[i];
        o = true;
    if (!o) {
      newprops[last] = myprops[i];

var css_ = selector + ' { ';

for (var i = 0, s = newprops.length; i < s; i++) {
  if (newprops[i]) {
    css_ += newprops[i].replace(/^\s*([^:]*)\s*:\s*(.*)\s*$/,
        '$1: $2; ');

css_ += '}';

// The final CSS is here!



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.