1. Code
  2. PHP

How to Squeeze the Most out of LESS

Scroll to top
Read Time: 26 min

During a sick day a few weeks ago, I got around to something I've been meaning to look at for about a year: LESS. If anything web technology is worth a look, I promise LESS is. In this article, we'll look at the amazing power of LESS and its ability to streamline and improve your development process. We'll cover rapid prototyping, building a lightweight grid system, and using CSS3 with LESS.

Getting Started: What We'll Be Using

For this tutorial, I will be using the PHP LESS implementation by Leaf Corcoran. This implementation is only one of many and the principles discussed in this tutorial should apply to any LESS implementation. Other versions of LESS include the original Ruby version and a JavaScript implementation.

Start by downloading the latest version of LESS. After you extract the file, you should have a 'lessphp' folder. Inside you will find a file called '': that's the one we want. Take this file and place it in your site's CSS folder.

Setting Up Your Master PHP Stylesheet

The way LESS PHP works is by parsing .less files and converting them to CSS, that the browsers can understand. LESS PHP can accomplish this task in several ways, but we are going to be using a simple PHP class method to parse the CSS; other methods are discussed in the LESS PHP documentation. All right, let's write some code.

Create the file styles.php in your site's CSS folder.

The first line is merely a means to gzip the final "CSS" file, reducing its file size; this is always a good practice. You could also do this via an .htaccess file.

In this code we are setting up the paths to our .less files (we'll add more later) and storing these paths in an array. The one thing about LESS PHP is that the parsing can take a while; it can take up to a few hundred miliseconds if you have 20K+ of .less file. It also uses server resources. If you are going to be using the PHP version, caching is a must. Let's see one way that we could accomplish this.

This code checks each of our .less files and gets the time each of them was last modified. This time is then compared to the modified time of the cache file, if it exists. If the cache file doesn't exist yet—or needs to be updated—we set $recache to true. Continuing on...

If we don't need to recache and the client's browser has a copy of the file already, we compare the timestamp of the client's copy against the latest modified file's timestamp. If the client has the most up-to-date version, we send a 304 response and the browser doesn't need to download anything. If the client doesn't have a copy yet or has an outdated version, we set the header on our PHP file to be a CSS document and set the last-modified time to the time stamp of the most recently updated .less file.

If we need to create the cache file or update the cache file, we bring in the LESS PHP file. We require it as opposed to including it, because this portion of styles.php will not work without it. Next we loop through the files, assigning their contents to a single variable $css which is parsed by LESS PHP, saved to disc for future caching purposes (only one visitor to the site is needed to cache the file for everyone), and the parsed LESS is output as standard CSS. If the client needs a version of the file (an update or for the first time) and the cached CSS file is up to date, we simply serve that file up, resulting in a significant speed savings.

Using LESS

Before we go too far, we need to create the styles.less file we referenced in styles.php.

For those unfamiliar with LESS, in this code we set a variable @h1BG and assigned it a dark green color. In the h1 rule, we made use of it three times: once we used the standard property, and the other two times we told LESS that we wanted the borders slightly lighter/darker than the background. LESS PHP performed the math on the hex values for us.

Now let's create a basic HTML document to make use of this new stylesheet.

If everything went right, you should see something similar to the following image. This is a good time to mention that for LESS, PHP syntax and formatting is very important. If you don't space your variables quite right, your entire stylesheet can vanish due a parse error. In other words, make sure you test the new sheet before pushing changes to a live site.

example of the h1 tag with green background, lighter bottom border, darker top borderexample of the h1 tag with green background, lighter bottom border, darker top borderexample of the h1 tag with green background, lighter bottom border, darker top border

If you take a peek at the source of styles.php in your browser, you should see the following:

Note that, not only is the variable appropriately applied, but the variable declaration doesn't appear in the final code. As a side note, LESS PHP condenses your CSS, but does not minify it.

Let's take things a little further now and see what else LESS can do. Make the following additions to your styles.less and HTML file (and while we're at it change @h1BG to @color4):

Firstly, those of you who are not familiar with LESS may be confused by the rules within rules concept, a.k.a. nested rules. What it means is you don't have to type #content h2 {...}, #content a {...} anymore. It also lets you structure your CSS better so you can clearly see the CSS inheritance chain.

For those of you coding along, you've noticed a few problems. The 1px border on #content is causing our ad section to drop below. This is the same problem you would get if you had defined the widths as 75% and 25%. As many of you know, margin, borders, and padding can wreak havoc with floated, percent-based layouts. So let's fix some of that; it would be nice if the content wasn't so bunched up. Make the following change to styles.less:

float problem before and afterfloat problem before and afterfloat problem before and after


As you can already tell, I'm not a designer (though the color scheme isn't a bad one *wink*). However, if I was, I would want the headers on the site to have similar characteristics. Let's do it the LESS way. Add the following to styles.less:

That is called a mixin; think of it like a CSS function. We can apply it to our headers. Make the following changes:

Let's take a look at just the header's CSS output to see if we can learn anything about LESS.

You can end up with a lot of duplicate code if you are not careful.

This is the main downside with LESS from what I can see: you can end up with a lot of duplicate code, if you are not careful. Be sure to consider what code you insert -- especially in mixins. In the code output we have a class .header that is not used, and multiple properties that are unnecessarily duplicated. Remember, when working with LESS, you are working with both it and CSS, so CSS best practices still apply. A better way to write this would be:

If we look at the code output now, we should see that the properties that should be grouped, are. The unique properties only show up in their respective rules and we don't have an unnecessary rule, .header, appearing in our css.

Unnecessarily Nesting Selectors

Another thing to be careful about is unnecessarily nesting selectors. If your CSS doesn't need to be that specific to work, don't nest it; it can be its own separate rule. LESS is here to help you write CSS, not to bloat your stylesheet. Don't use it to bring the DOM to your stylesheet; it's bad enough where it is. You don't want to end up with rules like #main .menu_items #center .menuTable table tr td.itemMoveDown a:hover {...}. For a reference point, take a look at the following:

Don't use less to bring the DOM to your stylesheet, it's bad enough where it is.

Above, if in your site #content is always inside #wrapper, you don't need to specify #contents within #wrapper, and so on. From before, if your document has tds that aren't within rows or tables, you have other problems. Again, before you nest, make sure it is saving you time and is necessary. As a general rule of thumb, never nest inside of body or your main div.

Ok, back to our example. So you've just shown the site to the customer. It was too wide for his smartphone, so he would like his site to be 800px wide instead. Oh, and he wants his colors to be a light blue and a dark blue, and the green should be an orange. Assuming he wants to keep the same proportions, how many lines do we have to change for the new layout and theme? Just four:

In the old days, with a larger site, this could mean digging through dozens of CSS files, redoing width calculations and updating multiple colors throughout. With LESS, it is trivial. Later we'll explore how you could take this concept even further.


  • LESS's syntax is similar to CSS.
  • LESS can do math on colors and units of measurement.
  • LESS variables can be used in multiple places in your CSS.
  • LESS can duplicate code, so use the same judgement you would with CSS.
  • LESS makes adjusting an entire site's CSS trivial.

A Flexible, Semantic, and Lightweight Grid

I don't know how many of you have worked with some of the popular CSS grid systems around, so let me introduce you to a few problems.

This code hyperbole has a point: frameworks can cause gross code. Our markup has developed a serious case of 'classitis', not to mention that none of the classes are semantic. The CSS isn't too much better:

It ends up being dozens upon dozens of lines...minified. Most grid systems also suffer from a problem we encountered before. What if I want to add a border to an element, or some padding? Up until now, if you were working in one of these systems, you either had to add an extra div inside your "grid div" which had the border and padding, or you had to overwrite your grid rule saying #content { width: 699px; } because it has a border and some padding. We also run into a pretty bad problem if the client changes the site width, as this CSS has been tailor made to a specific content width and column count.

Flexible Grid with LESS

Ready to build a semantic, flexible grid fourteen lines of code? Using only the knowledge we've already learned? Introducing grid.less:

Ok, so it was seventeen lines, but I don't want to count the closing brackets. Let's step through the code. First, we are defining a LESS variable, called unit. Each unit is 1/24th of the page width. Feel free to pick any number you are comfortable with. I chose 24 because both it and its half (12) can be divided nicely by 2, 3, and 4. Shortly, we'll find that it doesn't matter what number you put here, grid.less can handle anything you throw at it. One thing to note however: Webkit browsers would like you to pick a number of columns that is divisible by your site width, or else they may lose one or two pixels if you put a bunch of small grid units on a line. Chrome and Safari don't like percent-based layouts either if the percent ends up with partial pixels. Firefox and IE (surprisingly) don't care: they handle the difference by adding in the extra pixels throughout the elements, a pixel here and a pixel there.

On the second line, @gm stands for grid margin; on the next, @g stands for grid unit. Both are short to make it easier to type when applying, but having short names won't reduce your file size at all, because LESS variables and @-prefixed mixins don't get output to the final CSS file when the LESS files are parsed. You don't have to advertise your grid system in your CSS any longer since the grid magically disappears. Thanks LESS!

Back to the code. In the @g mixin, the first parameter is what unit the element is: 2, 4.8, 6, 12, etc. Wait...4.8? Sure; you wanted five same-sized boxes filling a row on the page, didn't you? 24/5.

The second parameter is the default margin we have between our page elements; it takes the value defined by @gm. Want them closer? @gm: 5px. Further? @gm: 10px or @gm: 12px. LESS can do it.

Looking at the code once more, you may notice we are lacking a wrapping element that most grid systems have. Or are we? Apply @g(12; 0;) to a rule. Done.

We also have the option to pass margin-top and margin-bottom into our grid function as the third and fourth parameters. This is nice for two reasons. First, it allows us to utilize the margin shorthand code; and second, we only have to manage the margins in one place, the mixin call.

Inside the mixin, we are pulling a slight trick. With LESS PHP the @gpadding and @gborder, which are used to do our width calculation, are always 0 unless they are defined in the CSS/LESS rule before we apply the @g mixin. In other versions of LESS, you may need to engineer a different reset such as passing it in as a parameter into the mixin.

@shift is used primarily to aid in SEO purposes. Generally, it is good practice to put your main content as early in the document as you can for search engines to give it a good weight. Sometimes, the designs we are given indicate that other content—such as a sidebar or advertisement—comes first. With shift, we can maintain good markup and still achieve our desired design. @shift can accept either positive or negative units. @newRow is merely a convenient reminder; it isn't really needed, as you can easily type clear: left on your own. If you do, we're back to those 14 lines I was hoping for earlier.

Our Grid in Use

Enough talk, it's time to see an example so we can wrap our heads around all of this. Let's start the code fresh. In styles.php we will now have 3 less files: settings.less, grid.less, and styles.less. Settings.less will get our color scheme variables, the heading code, and the site width. Don't forget to wipe styles.less so we can work with some new markup. Let's also make movie5.html.

Your file array in styles.php should look like the following:

The markup for movies5.html:

Our new stylesheet for styles.less:

Assuming copy-and-paste worked, you should end up with something close to this:

example grid layoutexample grid layoutexample grid layout

A few notes on the previous LESS code. If you take a moment to study it, you will notice multiple times that I used the @g mixin to control vertical height, as well as the regular grid specification of the number of columns an element takes up. When defining top and bottom margin, if the element was not a wrapping element, I always passed in @gm as the second parameter to the mixin. I did this instead of entering the value that @gm was. The reason for this is that it only leaves one place if we decide we want to adjust the horizontal spacing between grid elements.

Also of note: whenever you define border or padding, you need to set @gborder or @gpadding to the sum of the respective horizontal units. Be sure to remember that a rule like padding: 5px; means 10px of total padding. Lastly you may have noticed an & in the code. With LESS PHP this is a joiner and results in li.selected. I could have just as easily moved .selected out of the li rule but still within the #site-navigation rule to achieve the same effect (it is actually 2 characters smaller in the CSS if you do).

It may not be THE perfect grid system, but I definitely think it can be with a little more work. It allows for semantic markup, avoids classitis, and can result in potentially a much smaller CSS footprint, since you only output the code you actually need. If you have any suggestions, please let me know by using the comments below.

I would be ungrateful if I didn't offer some special thanks to Kyle Blomquist, with whom I tossed around a few ideas.


  • Mixins can be used to define more complex systems. Figure out a problem that can be solved with math and create your mixin to put idea to browser.

Cross-browser CSS3

What's a tutorial these days without CSS3? LESS can make it easier on designers since they don't have to remember the cross-browser syntax differences. Create css3.less and add it to styles.php. We'll start with something basic, like a nice linear gradient.

Well, if you haven't done it much, you'll soon realize that CSS3 rules are implemented somewhat differently when it comes to Firefox, Webkit, or not at all when it comes to IE pre-9. As a result, it limits LESS...slightly. For example, Firefox allows you to specify the degrees a gradient travels, but Webkit is limited to top left bottom left type definition. IE only has a filter with two types: vertical and horizontal. As a result, if we want another direction, we have to make another LESS mixin.

We can avoid a little of the duplication if we move the clipping properties to their own mixin.

Still not great, and now we have two rules, but gradients should be working. So what else can we do with filters so IE can play too? Drop shadows? While we can attempt a few things using the other filters Microsoft provided, such as blur and shadow, most attempts don't match up well with the CSS3 implementations in modern browsers. Frankly, most attempts end up looking pretty awful or require extra markup. Gradients are by far the best looking. There are also some things that can't be done with filters such as rounded corners. I don't know about you, but I would like to use more properties than just gradients.


Thankfully, I found a nice project out there called CSS3 Pie. This Progressive IE Enhancement tool uses behaviors, a.k.a. what Microsoft was hoping would be reusable JavaScript snippits, to achieve many of the CSS3 effects. If you do want to go the filter route (since PIE relies on JavaScript being enabled), let us know if you fare better than I did using the comments section below.

We'll start by downloading the latest copy of PIE from the site. The file we need is; place it in your CSS directory. CSS3 PIE allows us to make use of linear gradients, rounded corners, and box shadows. Since we are a little more free now, let's see what we can come up with:

We ended up with one linearGradient mixin after all. Note that PIE requires position relative and has-layout because it is drawing a VML element behind our original html element. If you have some absolutely-positioned elements, you may need to be careful and re-define this property for IE.

Border radius is pretty straightforward; note however, that if we only want to round a portion of the element or have variable rounding, IE won't be able to since the VML is a rounded rectangle with a specific radius.

While I included some extra properties such as spreadRadius and inset here, CSS3 PIE doesn't yet support them. So, if IE is important to you, hold off on those for now.

While IE does have a drop shadow filter, it doesn't work reliably. Text shadows, if subtle, don't cause that big of a difference when it comes to page appearance, so being a little less cross-browser friendly here doesn't hurt too much.

Time for a quick example. Make styles.css3 and add it to your files array in styles.php.

Can you spot which is IE? Sadly, there is a clue, but it's a non-css one, so I guess that is OK.

Firefox, IE 8, and Chrome with css3 appliedFirefox, IE 8, and Chrome with css3 appliedFirefox, IE 8, and Chrome with css3 applied


All right, one last CSS3 property; let's see if we can do RGBA.

Well, it's definitely not the prettiest function, but it works. For cool browsers, simply pass in the first four properties like normal. If LESS PHP could do if statements, IE wouldn't require any special parameters, but no such luck. The long-looking hex is made up of two parts. The first two positions set the alpha, 00 for completely transparent, FF for no transparency. The last six positions is for the hex equivalent of the rgb. You may have to do a little math, but it works (make sure the long hex is in quotes). Also, in IE, you can't have rounded corners and RGBA, at least with this implementation. If you do try, RGBA will take precedence.

Getting the Most...Continue to Innovate

A few ideas for where you can go from here:

  • Make your stylesheet accept several $_GET parameters and set your @color1, @color2 ... variables, or even page width with these parameters.
  • In styles.php set up some color schemes. Makes it easy for you to change themes quickly to get that perfect combination for a client.
  • Make a JavaScript theme-switcher based on the same idea.
  • Take the variables even further using mixins. Have a menu? Prepare for both horizontal and vertical using two mixins. Switch using parameters.
  • Skin your favorite applications/frameworks—such as WordPress, Magento, Drupal, CakePHP, etc—using LESS. It makes things a lot easier if the site isn't confined to a single application and you need your app to match someone's HTML page and its existing color scheme.

I've only been playing with LESS for a few weeks and these are the ideas I've come up with so far. What are yours? Please share them with the community below.

You Also Might Like

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.