Beautify Your LESS Stylesheets With Indentation Etc

After a couple of cut and paste jobs I had some LESS files with really ugly looking indentation. After a fruitless search for a tool to auto-format my LESS stylesheets, I decided to build a quick and dirty php script to do the job.

I’m a notepad++ user and while it comes with some nice auto-formatting functions that provide the proper indentation and such, it chokes on LESS stylesheets. I’ve tried other editors such as Crunch and SublimeText but they don’t provide auto-formatting for LESS either, not even through a plugin package.

There are quite a few online code beautifiers that do a fine job with formatting ordinary CSS, but present them with nested styles and parametric functions and they all turn to mush. What else is there to try? Well I decided it wouldn’t be that hard to code a php script and here it is:


/* Quick and dirty way to clean up LESS stylesheets
* !Warning! don’t run this on a live webserver online, use it on localhost or adapt the code to make it safer
* This code doesn’t reflect perfect coding practices, it’s just a quick and dirty script to quickly format Less files.
* The clean_up_less function will sort out indentation, trim whitespaces and add whitespace
* If you have a missing or extra bracket somewhere, you will have bad results.
* The code only adds tabs for indentation and removes/adds whitespace so your Less won’t get borked

<form method=”post”>
<input type=”submit” value=”format less” />
<textarea name=”nonformatted” id=”nonformatted” style=”display: block; position:relative;float:left;width: 45%;min-height: 400px; height: 100%;”></textarea>
<textarea name=”formatted” id=”formatted” style=”display: block; width: 45%;position:relative;float:left;min-height: 400px; height: 100%;”><?php
if ( $_POST[“nonformatted”] ){
echo clean_up_less( $_POST[“nonformatted”] );
function clean_up_less( $css ){
$lines = explode( “n”, $css );
$currentnest = 0;
foreach($lines as $line){
$newline = trim ( $line );
$newline = str_replace( ‘{‘, ‘ {‘, $newline); // make sure left bracket always is preceed by whitespace
$newline = preg_replace(‘/ss+/’, ‘ ‘, $newline); //remove extraneous whitespace
$pos = strpos ( $line, ‘}’ );
if ( $pos > -1 ){
$currentnest = $currentnest – 1;
$tabs = ”;
$i = 0;
while( $i < $currentnest ){
$tabs .= “t”;
if( strpos( $line, ‘{‘ ) ){
if ($currentnest > 0 ){
$newcss .= $tabs.$newline.”n”;
} else {
$newcss .= $newline.”n”;
return $newcss;

It’s not a world class script but it got the job done for me. If you’re running a local server setup you can quite easily plug in this script and beautify your LESS in the blink of an eye.

Got a better way to do it? Did you find a tool or plugin that can format LESS stylesheets? Please let it know in the comments because I’d love to know.

*update* does a pretty good job at this too


Leave a Reply

Your email address will not be published.