Sorting and Organizing CSS Using CSSComb

Compared to other web-related languages, CSS is relatively straightforward and easy to write. But at the same time, it is also hard to organize, particularly when it comes to codes that consist of thousands of lines.

It would be great if we’re able to organize CSS and make it easier for other developers to read and maintain the codes – which is useful if you are working in a team.

In this post, we are going to show you how to sort and organize CSS using a tool called CSSComb. But first, let’s take a look at a short example on CSS property ordering.

Technically, CSS has no restrictions when it comes to ordering properties. The following example…

 .class { background-color: #f3f3f3; width: 100px; height: 100px; font-color: #000; } 

… will output the same result as the following:

 .class { width: 100px; font-color: #000; background-color: #f3f3f3; height: 100px; } 

But as we’ve mentioned previously, being organized will help your teammates easily maintain your codes. Sorting CSS codes, however, requires a lot of cutting & pasting, and thoughts on how to order it. And that’s where CSSComb comes in handy.

How to Use CSSComb

CSSComb is a sorting utility for CSS that is built by Slava Oliyanchuk. CSSComb supports CSS2 to CSS4, and is available in many popular code editors such as TextMate, Coda, Notepad++ and Sublime Text, as a plugin or an extension.

If you are using Sublime Text, CSSComb can be installed easily via the Package Control. Once installed, you can sort the CSS properties in several ways:

  • Hit the default key combination: Shift + Ctrl + C.
  • Right-click and select: Sort via CSSComb option.
  • Open Command Palette – Command + Shift + P and select Sort via CSSComb.

In this example, we have the following style rule.

 .class { padding-top: 1px; border-left: 1px solid #fff; -moz-box-shadow: 0 0 1px 0 #000; -webkit-box-shadow: 0 0 1px 0 #000; box-shadow: 0 0 1px 0 #000; border-right: 1px solid #fff; height: 23px; padding-bottom: 10px; background-color: #fff; } 

The style rule above works, and there is nothing wrong with it, except that it’s a bit unorganized. Now, after running CSSComb, the properties are sorted in the following order.

 .site-header > .container { padding-top: 1px; padding-bottom: 10px; height: 23px; border-right: 1px solid #fff; border-left: 1px solid #fff; background-color: #fff; -webkit-box-shadow: 0 0 1px 0 #000; -moz-box-shadow: 0 0 1px 0 #000; box-shadow: 0 0 1px 0 #000; } 

Above is the default ordering rule in CSSComb, but if you don’t want to order it like that, you can customize the order, by going to the Preferences > Package Setting > CSSComb menu, and set ting a new order rule under Sort Order – User.

Note: If you are using a code editor that does not have the extension or plugin, CSSComb is also available as a webtool.