A Comprehensive Introduction to LESS

Ivaylo Gerchev

If you’re reading this, you’ll already know that CSS is an easy to learn, and use, stylesheet language, which makes our websites shine. With the new CSS3 features being introduced, the possibilities are even greater. In this article I will cover the basics of LESS. Next Tuesday, we take a deep dive into it, covering Mixins, functions and even more!

All that sounds great, but this story has one weakness. CSS is static. And this means we repeat code over and over in our stylesheets, thus making the DRY (Don’t Repeat Yourself) principle only a dream. Fortunately, LESS can fix that. According to lesscss.org, LESS is a dynamic stylesheet language. What makes LESS dynamic, is that it extends CSS with variables, mixins, operations, and functions, forcing CSS to behave more like a programming language. But a key feature, is that it also preserves the original syntax used in CSS-with a few exceptions.

Technically speaking, LESS is a CSS preprocessor. In simple terms, CSS preprocessing is a method of extending the feature set of CSS by first writing the stylesheets in a new, extended language, then compiling the code to pure CSS so that its readable by browsers. LESS is one of three popular CSS preprocessors-the other two are Sass and Stylus.

I’ve chosen LESS because its designed to be as close to CSS as possible, so the syntax is almost identical to your current CSS, meaning you can use it right away with your existing code. All you need you learn is a new way of using the same language.

LESS can be run on the client or server side (with Node.js). For this tutorial, we’ll use LESS on the client side as its easier to get started. So, what are we waiting for? Let’s get started!

3, 2, 1… Getting Started

Using the JavaScript compiler is extremely easy. Simply include the script in your HTML code—it will process LESS as the page loads. We can then include our LESS file just as we would a standard stylesheet. Here’s the code to put between the <head> tags of your mark up:

<link rel="stylesheet/less" type="text/css" href="styles.less">
<script src="less.js" type="text/javascript"></script>
<script type="text/javascript">
  less.watch();
</script>

The stylesheet link goes above the script to ensure it is available for the preprocessor. Notice that the typical rel="stylesheet" has become rel="stylesheet/less". Also, make sure that the href value points to the location of your .less file.

If you wish, you can reference the less.js script directly from the Google Code server. With this method, you don’t even have to download the script to use it.

<script src="http://lesscss.googlecode.com/files/less-1.2.2.min.js"></script>

As you can see, we declared a stylesheet with a rel attribute set to stylesheet/less and created a file called styles.less. All our LESS and CSS code will go in this file now. We also declared the LESS JavaScript file that will compile our LESS code into CSS. This JavaScript file will perform some AJAX calls to read your LESS files, so you need to use a web server. If you don’t have one, just download WAMP (Windows), MAMP (Mac), or LAMP (Linux), depending on your operating system, and you’re ready to go.

The second script activates the ‘Watch’ mode in LESS, which is a client-side feature available in development mode. This will refresh the CSS on your page whenever your .less file is saved with new changes. The best thing is that it won’t refresh the whole page—just the right bits of CSS. It’s optional, but I think it’s too good not to use.

If you open the style.less file in your favorite editor, you’ll notice that since you’re editing a .less file, you don’t get any syntax highlighting by default. To fix this, just find your editor’s preferences where you can choose which files should be associated with CSS highlighting. LESS and CSS syntaxes are very close. Even if a little different, it should work fine.

Importing

You can import .less files, and all the variables and mixins inside them will be made available to the main file. The .less extension is optional:

@import "typography.less";
@import "typography";

If you want to import a CSS file, and don’t want LESS to process it, just use the .css extension:

@import "typography.css";

Before you skip this step away, I want to tell you that importing can be very powerful. At the end of your development phase, all .less files will be compiled and minified in one pure .css file, ready for production. So, you don’t need to worry about how many server requests your page will make, and whether this will slow down the page load. I think you will agree that maintaining one long .css file is far more difficult than several, separated, short files. So, it’s a good idea to split your main file into several specific files for colors, typography, grid, reset, etc. This will help you to structure your code in a more modular way.

Commenting

Commenting makes your code more readable. You can use comments in your .less files in the same way you do in regular CSS, but you have to bear in mind the following:

Multiline comments are preserved in LESS:

/* Hello, sir! This will be shown in your compiled file */
.class {color: white}

Single-line comments are “silent”, they don’t show up in the compiled CSS output:

// What's up,  dude? Don't worry, this won't show up in your compiled file
.class {color: white}

Variables or Constants?

LESS gives you ability to use variables just like you would in other 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.

Variables are declared and used with the @ symbol. You give them a name and a value, and then you can refer to the name of the variable anywhere in your .less file:

@name: value;              // syntax
@color: red;               // example
background-color: @color;  // usage
background-color: red;     // output

LESS also allows you to define variables with a variable name like this:

@mainColor: red;
@bgColor: 'mainColor';
background-color: @@bgColor; // background-color: red;

Before moving to more complex examples, you need to understand that "variables" in LESS are actually constants, which means they can only be defined once, and their values cannot be changed once set.

Don’t you think that as human beings it is far more natural for us to use colors with their real names rather than HEX or RGB values? Yeah, man! Me too, buddy, me too. Fortunately, this can be done easily with LESS. Let’s see what I mean:

//Define Color Palette
@dimGray: #696969;
@gold: #FFD700;
@greenYellow: #ADFF2F;
@deepSkyBlue: #00BFFF;


//Define Color Scheme
@backgroundColor: @dimGray;
@primaryColor: @gold;
@secondaryColor: @deepSkyBlue;


//Now you can use it like this:
section {
   background-color: @backgroundColor;
   color: @primaryColor;
}


section ul li {
   color: @secondaryColor;
}

Any time we want to use these colors in our design, we use the same CSS we always do, but insert the variable name instead of the color code. If you want to go deeper, you can create a separate file with color variables (colors.less) and just import it to your main .less file. This way, you don’t need to define colors for every new project. Just import and use.

Variable declarations will not appear in the output. They can hold any CSS property value, and can be declared in the outermost scope of the file, or anywhere else a CSS property may appear. Scope in LESS is very similar to that of most programming languages. You could use variables with the same name in various places. Variables and mixins are first searched for locally, and if they aren’t found, the compiler will move up the hierarchy until it finds them:

@color: red;
header {
  @color: white;
  color: @color; // white
}
footer  {
  color: @color; // red
}

You may have noticed that in all examples above, I’m using Hungarian notation – lowercase for the first word, then uppercase for the first letter of the following words – for my variables. It’s just my personal preference, it helps me to differentiate LESS from pure CSS. You could also use the CSS-style naming convention with dashes-between-lowercase-words, if you want to. It’s totally up to you.

We know how to set up our variables so it’s time to make some more advanced decisions.

And Next Time…

Stay tuned for part two in this series, where I will introduce you to the more advanced parts of LESS – Mixins and more!

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • http://www.tyssendesign.com.au John Faulds

    In my experience, if you only mention javascript dependencies for getting something to work, some people will instantly write off whatever you’re talking about, so you should probably also mention that there are a couple of compiler apps for LESS (Less.app, Codekit and LiveReload exist for the Mac, sorry don’t know about Windows) which means you don’t have to rely on js in your page to compile LESS files which means you just link to a normal CSS file instead.

    • Pat

      Win.less is a decent compiler.

    • ralph.m

      “In my experience, if you only mention javascript dependencies for getting something to work, some people will instantly write off whatever you’re talking about”

      Heh heh, you got in just before me. CSS styles that depend on JavaScript being available? That just doesn’t sound viable to me. Either the server-side option or the apps are a must. But for me, plain old CSS will remain preferable. I don’t find it’s hard to organize CSS files so that there’s little repetition.

    • Jamie

      Totally agree here, you don’t need to use the javascript solution on anything but a development environment.

      I run Win.less on my pc and am happy in the knowledge that it sits in the background working away without me thinking. No extra work flow, no dependencies and minified code uploaded to the live site.

      In a team environment working with less gives another layer of separation from the logic of a project. Only the back end devs have access to the business logic, the front end devs like myself concentrate on the front end code and using less we can let the designers play with the css variables until the cows come home without ever worrying about our core css files and our in house code structure being edited by those that aren’t comfortable with it.

      In conclusion Less rocks!

  • http://www.lauralock.com Laura Lock

    Looking forward to more in this series, and learning about LESS! Thanks for the intro, loved it.

  • Tjorriemorrie

    I think you should rather state your notation follows lowerCamelCase. Hungarian is more associated with pirating, e.g. $imoARR = array(‘justsayin’);

  • http://dichev.net Jordan Dichev

    Using it alot lately and looks like a very cool approach to authoring CSS for apps.
    But there is one great disatvantage – although code is looking pretty cool in the app, once it’s interpreted it’s a pain in the butt to debug the resulting CSS with it.

    • Pat

      Not sure what you mean by that. Are you getting minified output? If so there’s a way around that. I actually use a compiler to produce a css file but either way I think you can add a line of code at the top to fix the problem.

  • http://www.penumarthy.com Shashi Penumarthy

    If you’re on .Net check out http://www.dotlesscss.org

  • http://www.ifultech.com George Yoder

    Great article, look forward to part 2. An interesting alternative to the JS compiler, if your using Visual Studio, is the Pre-Build Event Command Line from the Build Properties Tab. using this command:

    “$(SolutionDir)packagesdotless.1.2.1.0tooldotless.Compiler.exe” “$(ProjectDir)cssfixed.less” “$(ProjectDir)cssfixed.css”

    You can have your .less file compiled into css prior to building your site. Then in your code you can:

  • Grant Parks

    Preprocessing is a cheat/hack. If you’re going to throw preprocessing into the mix, you should be able to do a lot more than make “CSS dynamic”

  • http://www.ziolo.be Greg Herb

    LESS is something I dreamed about. It’s easy and clean. For now, I’ll use LESS with all my projects. Thanks!

  • Chris

    Nice article, but..
    “This JavaScript file will perform some AJAX calls to read your LESS files, so you need to use a web server” isn’t really accurate.

    You don’t need a server on a ‘less’ only site as it (the less.js) doesn’t use AJAX to fetch the .less file, which is the exact reason why you need to include the .less file before the .js, as the .js file needs the .less file to be already loaded.

    Cheers

  • Al

    I question the need to add extra layers to the workflow with preprocessors. Is one doing more work or less? Afterall you still have to take the time to define those variables. Then you have to load extra js.

    With a little planning and a handy notepad by your keyboard, plain ol’ CSS can be just as easy to manage.

    • Al

      I should have mentioned that one can always use zen coding to predefine things like colors in your favorite IDE. For instance, while editing a css file, typing “deepSkyBlue” and hitting enter would expand to “color: #00BFFF;”.

  • Anton

    I’m curious why you wouldn’t just use php to create your CSS file if you want to preprocess; I much around with my school website and depending on the season/holiday/whatnot I often change the colour scheme, I simlpy put all my CSS in a PHP file which first imports color-xxx.php which contains the variables for the colour scheme and then I just echo the variables in my CSS….?

    I’m assuming that LESS has some more “robustness” to it….? I will stay tuned!

  • http://neighborwebmaster.com Kepler Gelotte

    Here’s why I don’t like Javascript solutions to critical processes. Go to http://lesscss.org/ with Javascript turned off in your browser. I know there are compile solutions for less, but now that adds an extra step even when making a simple CSS change. I am going to continue to use my PHP server side code which allows passing arguments on the CSS Url to make your stylesheet truly dynamic. It’s available here: http://coolphptools.com/dynamic_css in case you want to try it out. It’s free, open source and can be extended which some PHP knowledge.

  • http://www.devilthemes.com Devil

    I am not sure if I am wrong wheneverI look my site in IE 8 Browser (Buggy Browser) it get’s hangup and less js makes me hang again and again. Is there any solution ?

  • http://daz4126.com DAZ

    Nice article Ivaylo.

    Personally I prefer Sass, but LESS is awesome … anybody not using a CSS pre-processor is soon going to get left behind in the web design game.

    The people who thinks this is cheating, too much extra work or thinks they can already do this stuff with normal CSS really doesn’t get it. I’d recommend sticking around for future parts of this series because LESS can do a lot more than just remember names of colours and organize your files.

    I agree with the concerns over reliance on JavaScript though … really you should be using a server side solution and compiling it into an actual CSS file for production – LESS should only be used to make development faster.

    DAZ

  • Mark Roberts

    I can see the advantages to it definitely, but also the drawbacks as mentioned in regard to javascript usage and also just the fact that however similar to css it is it still adds another layer of complication, I think it probably comes down to how much and what sort of work you are doing, I can see that if you are writing a large amount of css on a daily basis it will improve your efficiency, but otherwise as noted above there are some pretty simple techniques for organising colours at the top of your stylesheet etc, plus there’s always the find and change function for global changes.

  • http://www.webmentor.cr/ Marco

    I am going to make the plunge from static CSS to LESS or SASS. Which one do you recommend?

    • Ivaylo Gerchev

      I recommend LESS, because it’s simple and easy to use and implement, close to the CSS syntax which you already know, and has nice GUI compilers for all major platforms. In my opinion SASS is a little bit more complicated. That’s why I consider LESS as a better choice, especially for beginners.

      Cheers

  • http://morecss.org MoreCSS

    Nice article, but I’m not sure people are looking to cut down on repeated code. From our experience people want something that is human readable. In fact, taking the time write things out in long hand can greatly improve flexibility.

    That is why we built moreCSS (morecss.org). See what you think and let me know if you have any feedback.

  • Christian Schiffer

    These less constants, I have only seen them in use in regard to color. Would it be possible to make other or more complex constant types like @Grid = border-color: red; border: 0,0,0,0; width: 100%?