close

Day 1: Learn to use LESS

LESS is a dynamic style sheet language. It’s like CSS but much more powerful, saves time and has a bunch of neat features rolled in to make our lives easier. I’m going to run you through setting up LESS, some of its features and finally, writing some LESS.

As mentioned above, LESS is like CSS but with added features. These are added into our LESS style sheets and then converted to regular CSS via a pre-compiler. This can be done in one of two ways:

  1. Loading the LESS.js file in your tags. This will take any .less style sheet files and parse them through the LESS.js file and output regular ol’ CSS which your browser will understand and render.
  2. Download the LESS.app / Codekit (or your OS equivalent pre-compiler) which will parse your files locally and create the regular .css files alongside your .less files. For the purpose of this introduction, we’ll be using LESS.app on OS X.

So let’s get started shall we?

First off – in your code editor of choice – create two new files. One called style.less and one called style.css. The CSS file is what you’ll reference in your HTML but it’s the LESS file where you’ll be inputting your CSS.

Open up LESS.app. If this is the first time you’ve used LESS.app, you’ll be greeted with a ‘finder’ type window. Add your project folder by hitting the + button to the bottom left. If you choose the root folder of your local site, LESS.app will find all .less files within and starting watching those files (it’ll list them for you).

If you want to store your CSS file in a different location, hit the cog in the bottom right hand corner and choose ‘Set CSS output path’. Otherwise, LESS.app will output your CSS file in the same directory as your LESS file.

Now you’re all set up. LESS.app will watch your .less files. Once you’ve saved some CSS to your .less file, LESS.app will be notified and will compile all that CSS into your style.css file. Normal CSS will copy over just fine. If you’re using LESS, it’ll compile and work its magic.

Let’s look at some examples…

Variables

When you’re designing or coding a website, you’ll generally have a colour palette to work with. For example, let’s say you’ve got a main colour of orange (#fc0) and an accent colour of dark grey (#656365). Instead of declaring these colours multiple times throughout your style sheet, you can apply variables with LESS. Generally, these go at the beginning of your LESS file:

@maincol: #fc0;
@accentcol: #656365;

Now you’ve declared your variables, you can call these in your style sheet as follows:

a { color:@maincol; }
a:hover {color:@accentcol; }

Once LESS.app has compiled your style sheet, it would output the following styles into your .css file:

a {color:#ffcc00;}
a:hover {color:#656365;}

Nifty, eh?

You may be wondering how this’ll save you time, seeing as it’s almost exactly the same amount of characters. In an average style sheet, the main branding colours are specified multiple times across multiple elements. Just imagine you decided to swap out those colours with different colours because the company has had a rebrand. Instead of going through your style sheet replacing hundreds of instances of the main colour, you’ll just need to replace the variable @maincol at the top of the style sheet. Simple.

As an aside, variables that you declare in your .less file won’t be output in the .css file.

Mixins

Mixins are another cool feature of LESS. They allow you to specify a chunk of code as a class like you normally would with CSS, but then allow you to ‘mix’ those classes together.
There are two types here: the first is the mixin, the second is the parametric mixin. Sounds complex, but it isn’t.

Let’s use boxes as an example. Imagine on the site you’re coding, the design calls for various multicoloured boxes or sections. One might be yellow, one red, one green and one blue. You might do something like this:

.bluebox {
    border:1px solid #1946eb; /* Blue colour */
    background-color:#efe9fd;
}
.redbox {
    border:1px solid #a01f02; /* Red colour */
    background-color:#ffebe6;
}

Once you’ve specified your coloured boxes, you can mixin those styles. For our example div, we could do something like this:

div#example {
    .redbox;
}

This would then add the red border and background colour to our example div. and LESS will output the following CSS when compiled:

div#example {
    border:1px solid #a01f02; /* Red colour *
    background-color:#ffebe6;
}

Pretty sweet, eh? The next type of mixin is the parametric mixin. Sounds scary, but it isn’t. It’s almost identical to the normal mixin but will take arguments within parenthesis. The best way to explain is with an example.

Let’s use text-shadow as an example of a parametric mixin. First, we’ll create our ‘mixin’:

.boxshadow (@shadow:2px 2px 5px rgba(0,0,0,.4)) {
    -webkit-box-shadow: @shadow;
    -moz-box-shadow: @shadow;
    box-shadow: @shadow;
}

I’m not going to lie, on first inspection that does look pretty complex, so let’s break it down.

Specify your mixin name just like you would a CSS class followed by parenthesis. Within the parenthesis, you can specify a variable (we covered these previously) followed by a value. This value becomes your default for the selector. In this case, our default is now ‘2px 2px 5px rgba(0,0,0,.4)’.

By setting the variable ‘@shadow’, we can then use that default code elsewhere in the mixin. Referring back to the example above, specifying ‘@shadow’ after each declaration would mean that once compiled, the CSS will instead show ‘box-shadow: 2px 2px 5px rgba(0,0,0,.4);’.

But that’s just the first part. Once you’ve set up your mixins they can be called elsewhere in your LESS style sheet. As an example, let’s say you wanted to include a div at the end of an article but you also wanted to apply the box shadow to that div, you’d simply type the following:

div#example {
    .boxshadow; /* notice this is our mixin */
}

Easy as pie, and it can be used multiple times.

But remember those parentheses we used earlier to set a default for our box shadow? That can easily be over-written:

div#example {
    .boxshadow(0 0 5px #f00); /* default shadow overwritten */
}

This will add our box shadow elements to our div, but will change from an offset dark grey shadow to a red glow spreading evenly from all sides.

Excellent stuff, and there’s more. You can also utilise variables (again) so let’s put our main colour (#ffCC00) to good use and set it as our shadow colour.

div#example {
    .boxshadow(0 0 5px @maincol);
}

Job done! You’ve now got your main orange colour as your shadow on your div.

So once that’s all run through your pre-compiler, you’ll have the following CSS:

div#example {
    -webkit-box-shadow: 0 0 5px #ffcc00;
    -moz-box-shadow: 0 0 5px #ffcc00;
    box-shadow: 0 0 5px #ffcc00;
}

No sign of any LESS in the outputted code and lots of time saved!

Essentially, mixins are chunks of code that you can write several times during a normal site build. You can then group them together and call them with one class name – even better if you can mix it up with some variables too.

Nested rules

Another simple yet powerful time-saving feature of LESS is nested selectors.

You can write new CSS rules within the curly braces of existing rules. Once compiled, the rule within will be output within the parent, then they’ll be extrapolated as required. Here’s an example of an element with a H1, P & Span all nested.

section#about { 
    .boxshadow(0 0 5px @maincol);
    
    h1 {
        font-size:1.4em;
    }
    
    p {
        color: @accentcol;
        
        span {
            color: @maincol; /* Notice the span element declared within the P tag */
        }
    }
}

When you run this through the compiler, you’ll actually get the following CSS:

section#about {
    -webkit-box-shadow: 0 0 5px #ffcc00;
    -moz-box-shadow: 0 0 5px #ffcc00;
    box-shadow: 0 0 5px #ffcc00;
}

section#about h1 {
    font-size:1.4em;
}

section#about p {
    color: #656365;
}

section#about p span {
    color: #ffcc00;
}

It seems like there’s a lot more code and plenty of repetition in there when cycling through the elements to build up your declaration.

Nested rules do become easier when you’re building the style sheet to a site as a lot more rules can be nested, saving you even more time.

OPERATIONS

The final feature, and probably the most advanced of the four main features of LESS is the operations feature. Operations are essentially functions or modifiers you can apply to your rules.

Operations on measurements

Operations utilise some basic maths to modify your properties – this may sound scary but it’s not. Let’s assume you love 20px padding everywhere on your page and you’ve set up a variable:

@padding: 20px;

You’ve used that all over your site but you realise your footer needs to be a bit further away from your content. You could use:

footer {
    padding-top:@padding * 2;
}

This will compile to padding-top:40px; because it’s taken your original 20px from your variable and multiplied it by two.

Maybe that doesn’t give you enough control though, and you only want to add 10px to that padding:

footer {
    padding-top:@padding + 10;
}

LESS is aware that you’ve used the ‘px’ measurement in your variable so will add 10 onto that to create 30px padding on your footer – you don’t need to specify the measurement unit.

If you changed your @padding variable to 3em, you would need to change the modifier on your footer padding otherwise it’d compile to 13em (3em + 10) which would create a crazy amount of space.

COLOUR FUNCTIONS

For me, LESS has a whole bunch of features that make it awesome to work with. Variables are time savers and mixins make your code re-usable.

One final feature that I love about LESS is the colour functions.

As I mentioned right at the beginning, we can set variables using the ‘@’ symbol. As an example, ‘@bg: #fc0;’ will set the @bg variable to a nice orange. Every time we call @bg in our LESS style sheet, the compiler will swap it out for #fc0.

But what if we were building the UI and wanted to use some form of variation on the #fc0 colour? Say we wanted our navigation links to be a darker orange. Instead of going to find the RGBA/HEX code for the dark orange, we simply put:

color:darken(@bg,20%);

This colour modifier tells LESS to take our @bg color and darken it by 20%.
The same will work for lightening the colour too:

color:lighten(@bg,20%);

But LESS will do more than just darken or lighten colours. You can adjust the opacity by using ‘fadein/fadeout’.

The ‘fadein’ function will increase the opacity of an element by the specified percentage making it less transparent. However, it’ll only work on elements that have a value of transparency applied already. If you’re applying it to body text that you haven’t previously applied any transparency or opacity settings then – by default – it’ll be at full opacity and therefore can’t be increased.

Similarly, ‘fadeout’ function will decrease the opacity of an element by the specified percentage, making your element more transparent.

color:fadeout(@bg,20%);

The above will make the colour of our text 20% more transparent which means we will see some of the background pass through our text.

We can also adjust the saturation of our elements using ‘saturate/desaturate’ in our colour functions by setting our background colour to the following:

background-color:desaturate(@bg, 100%);

This will suck out all the colour from our element and leave us with a grey background. Maybe not the most useful of functions, but it does help when you’re working with a muted colour palette.

Just like the ‘fadein/fadeout’ function, the saturate modifier will only work on elements that have been previously de-saturated. Increasing the saturation on something already set at 100% will do nothing.

The last modifier is ‘spin’. Using Spin will adjust your colour based on the colour wheel. The syntax for this function is different to the previous three as it takes a degree value. The previous (fadein/fadeout, lighten/darken, saturate/desaturate) all take percentages.

For example:

background-color:spin(@bg,10);

This will spin the colour wheel by 10 degrees, which will turn our nice orange into a yellow.
Another example:

background-color:spin(@bg,-10);

This will spin the colour wheel in the opposite direction by 10 degrees (notice the negative 10). This will turn our orange into a red.

You can set the value to any number you like, but because it’s based on a circle (the colour wheel) you’d only use 1-360 (degrees). Anything above 360 and you’re starting back at the beginning again. If I was to use ‘background-color:spin(@bg,360)’, I’d get the same colour as when I started.

Those are the four core modifiers. You can of course, mix and match these too. Let’s say you like our orange but fancy using a light yellow, you can combine spin and lighten to achieve your colour as follows:

background-color:lighten(spin(@bg,15),40%);

In this example, we’ve got our @bg colour, which we’re spinning on the colour wheel by 15 degrees ‘spin(@bg,15)’ but we’re also lightening that colour by 40% too.

You can also create new variables using colour modifiers. As an example we’ll reuse the @bg example:

@bg: #fc0;

This sets a variable of @bg to orange (or #fc0). We could then create another variable with a darker tint by doing the following:

@darkbg: darken(@bg,30%);

So we’ve now set another variable (@darkbg) which will take the original background variable and darken it by 30%.

The beauty of this is that if you set just one or two colour variables in your .less style sheet and utilise the modifiers throughout the rest, then your whole design depends on that variable.

Fancy changing the orange to blue? Just change the variable and everything else will change to suit too, as the other colours are all dependant on the main variable. Marvellous!

OTHER LITTLE LESS FEATURES

COMMENTS

A little feature of note here: when you’re writing standard CSS, you can use the /* comment */ tags to comment your code. This is shown in your CSS publically.

You can use this in your LESS file too and they’ll show up just the same as you if you were working on a normal CSS file.

LESS has a silent comment feature where you can comment on your code using the double forward slash (//). This will leave your comments in your .less file but they won’t appear in your compiled .css file.

/* THIS COMMENT WILL APPEAR IN YOUR CSS FILE */
// THIS COMMENT WON'T APPEAR IN YOUR CSS

IMPORTING

You can import other .less or .css files into your .less file by using the following syntax:

@import "reset";

This looks in the directory your .less file is in for a file called reset.less (the .less extension is optional).

If the file you wish to import is already in a .css file, you’ll need to specify the extension so you would use this instead:

@import "reset.css";

ESCAPING

A small caveat here: as you may know, our dear old friend Internet Explorer doesn’t deal with transparent pngs very well (on older versions anyway), so you may have seen people using an old proprietary Microsoft selector called filter which looks something like this:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='image.png');

As you can see, it looks a bit scary, a bit long and a bit confusing.

You may also notice the colon in there following the progid. This causes a problem as it’s not valid CSS syntax and as such, will cause LESS to error. In order to get around this, we’ll need to escape the string using a tilde (~) and some quotation marks like this:

filter: ~"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='image.png')";

If we wrap our string in quote marks and precede it with a tilde, LESS will parse the string as is and will not try to compile it as CSS.

Conclusion

LESS is fast gaining traction (and a substantial user base) in the web development world. Some people do worry about LESS causing you to write lazy CSS, but I see it as an addition to my toolkit rather than just a tool to speed up development.

I love the way I can set a variable and re-use it throughout my style sheet. I love how I can set a mixin complete with arguments and utilise throughout. I love how I can create my own base mixins file which I can use across various projects and how LESS falls seamlessly into my style.

If you’re worried about learning LESS, don’t be – it’s extremely easy to pick up and to use. From a developer’s point of view, the only problem I can see is when you come across a project that’s written in raw CSS, the switch back to normal CSS may cause a headache or two. For something so powerful though, it’s a very minor issue.

Some resources to take a look at if you’re looking into LESS would be the documentation on the LESS CSS website.  LESS Elements is also a really handy resource. Lastly, Bootstrap from Twitter is an awesome utility which comes complete with a vast array of mixins already setup. It’s well worth a look!