Using Less.js to Simplify Your CSS3

by on 12th August 2010 with 93 Comments

screenshot

LESS is an amazing little tool that extends CSS with the addition of variables, mixins, operations and nested rules. What this means is that you can write leaner code very quickly. And with the recent rise of complex CSS3 properties, we have a few glaring examples of code that could definitely stand to be simplified a bit.

Today we’ll take a look at how to use the newest JavaScript implementation of LESS to simplify lengthy CSS3 markup. One of the key features we’ll be looking at that I haven’t seen discussed elsewhere is how to deal with multiple variables in mixins. It’s fairly simple but can be confusing if you’ve never tried it.

Anyone Can Use LESS.js

When I first looked at LESS, it seemed like an awful lot of work. There were all these weird compiling steps and Ruby scripts that ultimately felt like they were going to add time to my workflow instead of reduce it.

Fortunately, someone realized the whole process could be a lot simpler with JavaScript. So now implementing LESS is as easy as pasting two lines of code into your HTML and everything compiles automatically right in the browser! Let’s see how this works.

Getting Started

To make sure your LESS code compiles correctly, throw the following code into the head of your HTML.



Notice that the typical rel=”stylesheet” has become rel=”stylesheet/less” and that we’ve linked to a Google-hosted version of LESS.js.

The next step is to create a style.less file. This can be named anything you want, just be sure it has the .less extension instead of .css like you’re used to.

Declaring Variables

By far one of my favorite features of LESS is that you can use variables just like you would in most major programming languages. This makes it extremely easy to set global styles that can be changed in a single location rather than sorting through your code to find every instance of that style.

To see how this applies on a practical level, let’s set a couple of color variables. Imagine that our web page will have a primary and a secondary color that is used repeatedly throughout the design. Rather than remembering the color code every time, we can simply set these to variables.

To set a variable in LESS, use the @ symbol:

@primaryColor: #383939;
@secondaryColor: #66bbe3;

That’s it! Now any time we want to use these colors in our design, we simply use the same CSS we always do but insert the variable name instead of the color code.

background-color: @primaryColor;
color: @secondaryColor;

Now anytime we change the color in the variable declaration, the change will be automatically applied throughout the rest of the code anywhere the variable is called. This can definitely save you a lot of time when you start tweaking your designs.

Operations

Just as with JavaScript and any other programming language you’re used to, LESS allows you to perform operations on variables. This can save you a lot of mental math in the long run.

As an oversimplified example, say you wanted to create a box that was twice as wide as it was tall. You could declare the height in a variable and then set another variable that is twice that number.

@boxHeight: 200px;
@boxWidth: @boxHeight * 2;

Then later in your code you would use these variables to set the height and width of your box. If you were to then go back and change boxHeight to 400px, boxWidth would automatically be set to 800px;

height: @boxHeight;
width: @boxWidth;

Mixins

Here’s where the CSS3 will come into play. To start off, let’s look at the basic syntax for a random CSS3 property, say border-radius.

-moz-border-radius: 12px; 
-webkit-border-radius: 12px; 
border-radius: 12px;

As you can see, the current way to ensure that this works across the largest number of browsers is to include all of the various browser-specific versions. Above we used border-radius in conjunction with -webkit-border-radius and -moz-border-radius.

Any time we want to implement rounded corners in our CSS, we have to manually list all these versions. I see your brain ticking away and forming an argument about how you could simply set these styles to a class, but what if you wanted the flexibility to tweak the border radius on a per element basis? Setting up a reusable CSS class is a good solution, but you can take this idea a lot further with LESS.

LESS allows you to essentially set multiple variables into a single class that can then be embedded elsewhere in your code. To setup up a mixin using LESS, use the following syntax:

.roundedCorners (@radius: 12px) {
	-moz-border-radius: @radius;
	-webkit-border-radius: @radius;
	border-radius: @radius;
}

The code above sets a variable for the radius and makes it equal to 12px, throws it into all of the border-radius versions, then stores all of this information in a class called .roundedCorners.

Now when we want to apply rounded corners to an object, we simply toss in the class.

#box {
	background-color: @primaryColor;
	.roundedCorners;
}

This will apply a 12px corner-radius to our box div using all of the appropriate proprietary versions.

Remember that the 12px radius we setup in the mixin is merely a default that gets passed when no parameters are specified during the call. You can alternately insert that class and quickly set the border-radius to a different number.

#box {
	background-color: @primaryColor;
	.roundedCorners(20px);
}

This code still uses all of the different border-radius versions but will automatically stick 20px in as the value for the radius. This makes it super fast to implement custom iterations of a CSS3 property. Let’s go deeper down the rabbit hole and see how to do this with more complicated properties.

Multiple Variable Mixins

Border radius was a simple example because it only contains a single value to work with, but what about more complicated properties like box-shadow?

-moz-box-shadow: 3px 2px 5px #D4D4D4; 
-webkit-box-shadow: 3px 2px 5px #D4D4D4; 
box-shadow: 3px 2px 5px #D4D4D4; 

As you can see above, here we need to set four different variables to be uniform across the three versions. It may sound complicated but fortunately this works basically the same as it would in JavaScript. To keep the example simple, we’ll just use the default box-shadow to see how this is done.

.boxShadow (@hor: 3px, @vert: 2px, @blur: 5px, @shadow: #757171) {
	box-shadow: @hor @vert @blur @shadow;
}

Here we set variables for the horizontal and vertical offsets as well as for the blur radius and shadow color. Notice that these values are all enclosed in a single set of parentheses and separated by commas. Then on the inside of the brackets we write it out with the variables just like we did the numbers above, with no commas separating the values.

So let’s say we wanted to apply rounded corners, a box shadow and a transition to an item using LESS and CSS. The code you use would look something like the following:

/*Rounded Corners*/
.roundedCorners (@radius: 12px) {
	-moz-border-radius: @radius;
	-webkit-border-radius: @radius;
	border-radius: @radius;
}

/*Box Shadow*/
.boxShadow (@hor: 3px, @vert: 2px, @blur: 5px, @shadow: #757171) {
	-webkit-box-shadow: @hor @vert @blur @shadow;
	-moz-box-shadow: @hor @vert @blur @shadow;
	box-shadow: @hor @vert @blur @shadow;
}

/*Transition*/
.transition (@range: all, @time: 1s, @ease: ease-in-out) {
	-moz-transition: @range @time @ease;
	-webkit-transition: @range @time @ease;
	-o-transition: @range @time @ease;
	transition: @range @time @ease;
}

Then the implementation of these would be similar to the code below.

#box a {
	display: block;
	height: @boxHeight;
	width: @boxWidth;
	background: @primaryColor;
	.roundedCorners(20px);
	.boxShadow;
}
	
#box a:hover {
	background: @secondaryColor;
	.transition;
}

As you can see, we applied the variables for the height, width and color of the box, then implemented the roundedCorners and boxShadow classes. Finally, we created a hover event that transitioned the background color from the primary color to the secondary color.

Nested Rules

The example above can be simplified even further by utilizing LESS’s nested rules feature. Watch how we can throw all the box styles into the same set of brackets and eliminate the need to type out the div ID every time.

#box {
	
	a {
		background-color: @primaryColor;
		color: #fff;
		display: block;
		
		height: @boxHeight;
		width: @boxWidth;
		line-height: @boxHeight;
		
		margin: auto;
		margin-top: 50px;
		
		text-align: center;
		text-decoration: none;
	
		.roundedCorners(20px);
		.boxShadow;
	}
	
	a:hover {
		background: @secondaryColor;
		.transition;
	}
		
	p {
		font-size: 50px;
		font-family: helvetica, arial, sans-serif;
	}
}

As you can see, all of the box item’s link styles, link hover styles and paragraph styles are contained within the same parent.

Compiling

I know what you’re thinking, all of this is well and fine, but can I really use it? Does it load slower than standard CSS? What browsers support it?

It turns out all of these and other similar questions don’t really matter. The idea behind LESS is to speed up and simplify only the development step. This means what goes live on your final website should be plain old CSS, not LESS.

After you’re finished working on your site, you need only compile the LESS into CSS using your browser. To do this, simply open up your HTML file in a browser and view the source CSS. What you’ll see, regardless of what you actually coded, is a normal CSS structure. Simply copy and paste this into as CSS document and you’re ready to go.

Compiling with LESS.app

To make things even easier, you can completely automate the compiling process using the free LESS application.

screenshot

All you have to do is drag in the project folder containing your LESS files… that’s it! There’s no step two. As you continue to tweak and save your LESS files, a new CSS file will automatically be generated.

Conclusion

To sum up, LESS can now be implemented with only two lines of code in your HTML and can dramatically change the way you write CSS. Spend a few months with LESS and you’ll be creating and tweaking complex stylesheets faster than ever before.

You can use LESS to create variables, perform operations on variables, nest rules, and build complicated mixins to simplify your CSS3.

Leave a comment below and let us know what you think of LESS. Do you think it’s a great tool or a waste of time? We want to know!

Comments & Discussion

93 Comments

Comments & Discussion

93 Comments

  1. just as you said… if you dont want to use less.js in production you can “precompile” your less-code and deploy the good old css.

    i usually try to automate such tasks. For example by integrating it in my tool-chain.

    You are a java developer and you are interessted in running less.js? Here is something you may find interessting
    http://code.google.com/p/maven-less-plugin/

  2. Christopher says:

    Joshua, to take this a step further you can use the IE specific filters and eliminate images entirely for things like gradients.

    Less has been a lifesaver for me so far.

    Yevgeniy, thanks for the maven plugin link, that could prove to be very useful.

  3. I used the ruby version of LESS for a bit, and it was difficult to integrate into normal workflow. I’m very excited about the javascript version, and the compiling app. This Rocks! CSS just got an upgrade!

  4. Im using the .js LESS, and the new version is pretty cool (workin in IE6 too :) ).
    There’s a little things I do not make work. But I confess, I have to spend a time with this.

  5. Edward says:

    This looks amazing! I’m currently re-designing my website and I’m going to implement this immediately, today. I’ll see how I get on, but it looks like it has all the additional features CSS has been missing. Thanks!

  6. Thanks so much; this is a fabulous rapid-prototyping and Hack Day tool. For production you’ll want to pre-generate and have a live human engineer eyeball the resulting CSS, of course. :)

  7. Jason says:

    Just FYI:
    you can run less from command line too:
    “lessc file.less -w”
    this does the same thing that the Less.app does. That said, Less is awesome, my css is clean and allows for very easy theme creation.

  8. Steve says:

    I know from my experiments that less.js isn’t ready for proper use. The main issue was that when specifying image urls in css, it uses a relative path from the css file location. Whereas with less.js, it uses a relative path from the html file location.
    Thus making your files incompatible between regular less and less.js!

  9. I am confused by this statement:
    “This means what goes live on your final website should be plain old CSS, not LESS.”

    I wrote an article about LESS.js, and compare it to Sass 3. If you go to my link below, click on the demo, view source, then click on the CSS file, you will NOT see just plain CSS like you say. It displays the LESS code (so you see the variables and all). Did they change something?

    http://jc-designs.net/blog/2010/07/taking-less-js-for-a-spin-and-how-does-it-compare-to-sass-3/

    This is one of the reasons I prefer Sass over LESS.js. Using compass compiles it, and it outputs the CSS. LESS.js also adds an http request, whereas Sass does not. I know that is not a huge deal, but every bit helps. I don’t want to add more stuff to my web page, when I can do the same with Sass without it.

    Don’t get me wrong, LESS is great, and wins the ease of use for getting it to work. Personally though, Sass 3 wins.

  10. Crud…sorry, I meant THIS statement confuses me:

    “To do this, simply open up your HTML file in a browser and view the source CSS. What you’ll see, regardless of what you actually coded, is a normal CSS structure.”

  11. Joshua Johnson says:

    @Jeremy, if you follow the steps that I outlined above, you end up compiling your LESS. This automatically outputs simple CSS just like you’d write on your own.

  12. Less looks nice, but I’m already a happy SASS user (using sass –watch on the command line to automatically compile my scss into css as I make changes to my code) so I don’t see any advantage in switching.

  13. Ricardo says:

    The greatest advantage I see is that it works for windows developers “straight out of the box”. I’ve been using it for the past few weeks. It’s great for development but still very buggy on IE, so not ready for production, we have to compile and deploy the plain CSS.

    @Jeremy: actually LESS.js only adds an http request when the css is loaded for the first time (or modified), afterwards it’s kept in local storage.

  14. @Joshua Your compiling method (without the app) is to open your browser and view the source CSS (which is the link to the .less file). It shows the LESS code along with the CSS.

    http://jc-designs.net/demo/less.html

    I’m using 1.0.18 there. Is that a change they made in .21? Where you just see the compiled CSS? I’m pretty sure I’m not doing anything wrong, because my demo displays correctly, I just don’t see how you are getting the compiled CSS without the LESS, by just using your browser.

  15. Rizky says:

    I tried LESS once.. and I must say I was not pleased with the compiler output. it doesn’t handle multiple selectors very well.

    for example, a group of selectors like this:

    .class1, .class2, #id1, #id2 { ... }

    would be compiled into this:

    .class1 { ... }
    .class2 { ... }
    #id1 { ... }
    #id2 { ... }

    my CSS become very bloated. so I switched to SASS and I’m a very happy customer ever since..

  16. Paul says:

    I really want to start using this in my future projects, but as a few people have pointed out, the browser output is not compiled no matter how I’ve tried to view it, so those of us unfortunate enough to be working in a Window$-based OS are left without a way to compile it. Sure, I could also run Leopard on vmware and use the LESS.app every time I needed to compile it and then copy it back to my development environment, but that’s not a very practical solution.

    Don’t get me wrong, I totally love the concept and the implementation looks promising, but unfortunately I can’t see myself using it until there’s a way to compile it in a non-Mac environment. To be able to use variables with CSS would save me so much time in development it’s not even funny, but right now it’s just a tantalizingly, unreachable Shangri-La for me. Does anyone know if the LESS.app can be ported to Windows or used on a Linux production server? With any luck, there’s something that I’ve overlooked and a future post will point out my thick-headedness and show me the error in my assessment.

    Thanx in advance to anyone who can help me out!

  17. Marcin says:

    There is a php less compiler – http://leafo.net/lessphp/

    It can be used on a production server (the compiled css file is cached) or on virtually every development platform, be it Windows, Mac or any other where PHP may be run. It can also be used as a stand-alone command line tool.

  18. Alexander says:

    I’m not sure if I’m getting it all wrong but as I reeding it the less.js is supposed to interpet the .less file so it will be rendered as proper css by/in the browser.

    Well this is not happening for me in my chrome, safari or firefox.
    I’m not really sure if there is something I’m doing all wrong, but I’ve followed the instructs.

    I noticed that when I’ve changed the rel=stylesheet to rel=stylesheet/less it simply woulden’t take any notise of the .less file anymore.

    So any suggestions on what’s wrong on my end is welcome.

  19. Jaryl Sim says:

    @Alexander the JS file is not needed (or recommended) if you use the either the ruby or mac tool to precompile your .less file into .css.

    http://lesscss.org/
    http://incident57.com/less/

    Hope that helps!

  20. JoeZ99 says:

    Does anybody faced the following IE7 bug with less?

    in firefox and chrome, less can see this:

    @color: #fff;
    body{
    color: @color;
    ul {

    }
    }

    that is, besides the stuff, lesscss can also process the … stuff.

    But no luck with IE7 !!!!

  21. Lubo says:

    Hi guys, less.js looks pretty cool, but how can i force my dreamweaver to color the code. I mean, if I am editing a .css file, the code is colored so it’s easier to read and write. But if the file extension is .less, dreamweaver doesn’t recognise the file type and even doesn’t show up the “code hints” when typing.

  22. Lubo says:

    So the solution was pretty simple. Just in case somebody else would have the same problem:)

    http://www.last-child.com/set-up-dreamweaver-to-color-code-alternate-file-types/

  23. songxinwei says:

    songxinwei

  24. iansane says:

    “After you’re finished working on your site, you need only compile the LESS into CSS using your browser. To do this, simply open up your HTML file in a browser and view the source CSS. What you’ll see, regardless of what you actually coded, is a normal CSS structure. Simply copy and paste this into as CSS document and you’re ready to go.”

    View page source only shows the div and the link to the .less file. No css. Firebug shows the css but only the part that firefox actually used so the complete css is not shown. (only shows border-radius: 20px 20px 20px 20px;)

    I was able to use Pendule (free chrome extension) in chrome to see the entire css though.

    #mydiv {
    width: 100px;
    height: 100px;
    background-color: red;
    -webkit-border-radius: 20px;
    -moz-border-radius: 20px;
    border-radius: 20px;
    }

  25. jotis says:

    I see this is a rather old post, but I found it, so in case this helps:

    Not sure if any of the PC users having problems are serving up local content using IIS, but I had to add a MIME type in IIS for
    file name extension: .less
    MIME type: text/css

    That solved my problems so that I saw the rendered CSS in all browsers.

  26. paul says:

    thanks for this, the company i just started with use less for their dev work, so this article helped me get up to stratch.. cant believe i havent been using this for ages.. :)

  27. Anonymous says:

    Tip: you can also add #!watch to the the end of the URL and reloading (or calling less.watch() also works) will update the webpage as you save your LESS.

  28. Anonymous says:

    Also, if you are having problems, make sure less.js is included AFTER the code that you want it to parse.

  29. This is great. I was curious, do any of you use LESS in development for ExpressionEngine sites? If so, what has worked best for you?
    Cheers,

  30. jeff says:

    It’s really great to have such a wonderful tool.You don’t know how much I hate writing css files and now,I’ll save a lot of time.

Leave a Comment

Subscribe
Membership
About the Author