Making your CSS Dynamic with the Power of LESS

As a designer and theme expert for almost the past decade, I have seen many iterations of how our industry goes about creating a theme. The one constant for designers and theme developers is the use of CSS (Cascading Style Sheets). While yes there have been many versions and additions to CSS, it has remained relatively the same in the way we program it. My biggest complaint has always been the fact that CSS is a static language and contains no variables. This doesn’t sound like an issue until changes need to be made to the files afterwards.

Let me illustrate my point with an example. Instead of using #FF0000 to get a florescent red color, and use it hundreds of times in your style sheet, wouldn’t it be easier to store that color value inside a variable and just use that variable in all those places? That way if you want to recolor your webpage away from that florescent red to a less offensive color, you could just change the value of the variable in one place and that’s that.

Well my friends, Rejoice! LESS is here to make your CSS much more enjoyable.

Assumptions

It is good to note that some of the topics discussed below are meant for readers who have some basic Html and CSS knowledge as well as knowledge on coding structures. If your completely new I would highly recommend visiting http://www.w3schools.com/ to learn more about simpler techniques to get you started. That said …

What is LESS?

Less is a CSS pre-processor, meaning that it extends the CSS language, adding features that allow variables, mixins, functions and many other techniques that allow you to make CSS that is more maintainable, themable and extendable.

LESS is a superset of CSS. This means that all CSS code is valid LESS code but there are additional elements in LESS which would not be valid in CSS. This is great because your existing CSS is already valid LESS code, minimizing the learning curve to using LESS.

LESS adds much needed dynamic properties to CSS. It introduces variables, operations, function-like elements, even Javascript into the mix. It will make your life hassle free by enabling you to write stylesheets with a modular mindset.

Setting up and Using LESS

There are two ways to use LESS. You can create a LESS file and convert it on-demand using a Javascript file, or you can pre-compile it and use the resulting CSS file in your theme.

Option 1: Using The LESS Javascript File

The first option is very similar to adding jQuery to your site. First visit the LESS website and grab the Javascript file located in the download section. Once you have it, all you need to do is link it to your page like any other Javascript file.

1
<script src="js/less.js" type="text/javascript"></script>

Next, create a file with the .less extension and link it to your page with the code below:

1
<link rel="stylesheet/less" type="text/css" href="css/style.less">

Make sure that you link your LESS file before the Javascript file. Otherwise it will try to process the .less files before they are loaded.

Once you have this setup you can paste any previously existing CSS code into the LESS file or add an additional link to the CSS as LESS and CSS are compatible. While this method is the easiest for development I would recommend using the second method for your final production files.

Option 2: Compiling the LESS File to CSS

While this is a bit more tedious, in production scenarios this is preferred because the LESS processing will not be carried out by the users browser. LESS works by taking all the LESS code you write and converting it to CSS on the fly. Instead of having our site do this on demand we can convert our LESS file, save the CSS file output and use that instead of doing the on-demand conversion on each page load.

If your using a CMS like Drupal or WordPress you can find free modules that will allow you to compile these files for you directly on your web server instead of having your own machine compile these files.

If you’re developing a flat HTML site you can use Winless, a small local application which can detect all your LESS files automatically and whenever you save them it will convert them to a CSS file with the same name. This allows you to keep on linking to your CSS file on your pages while still utilizing the potential of LESS.

Start getting more with LESS

Finally, let’s start learning about writing LESS code. As you will see, if you understand CSS, LESS will be very easy to read and understand; it uses the same syntax style as CSS does, so it should all be familiar to you. Below

Variables the Key to LESS

This is by far the most basic and useful part of LESS. Variables in LESS work exactly like they do in Javascript and most other programming languages. You can use them to store a value and then use the variable name instead of the value itself whenever you need it.

1
2
3
4
5
6
7
8
@header-font: RageItalic;
h1, h2, h3, h4, h5, h6 {
    ;font-family: @header-font;
}
.large {
    ;font-family:@header-font;
}

In the example above we defined the @header-font variable and assigned the value “RageItalic” to it. We can now use this variable whenever we want to use the RageItalic font. If we decide we’d rather go with Helvetica as our heading font we don’t need to go through our whole file, we just change the value of the variable.

I find great use for variables when defining colors for a website. In the good old days (which weren’t that long ago) we used to do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
    Colors for our Website
    
    #ff0000 - Red – Links
    #cccccc - Light Gray - Borders
    #333333 – Dark Grey - Dark backgrounds and Heading colors
    #555555 - Mid Grey – Body Text Color
*/
body {
    background: #333333;
    color: #555555;
}
a {
    color:#ff9900;
}
h1, h2, h3, h4, h5, h6 {
    color: #333333;
}

There is nothing wrong with documenting your reused colors like this, it is good practice to help other designers using your stylesheets. The problem is that since it has nothing to do with the functionality of your stylesheet it has no other use than documentation itself.

With LESS we can modify our workflow and actually use our comments instead of it remaining as additional space in our file. This way if we want to make a change, it is 1 line replacement instead of finding a replacing multiple lines.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* Colors for our Website */
@color-red: #ff0000;
@color-gray_light: #cccccc;
@color-gray_dark: #333333;
@color-gray_medium: #555555;
        
body {
    background: @color-gray_dark;
    color: @color-gray_medium;
}
a {
    color:@color-red;
}
h1, h2, h3, h4, h5, h6 {
    color: @color-gray_dark;
}

An important thing to note is variables in LESS act like constants. This means that they can only be defined once – as opposed to variables in other languages which can be defined as many times as you’d like. So it is good practice to define all your variables at the top of your less documentation.

Mathmatical Operations

Another fun addition with less is the ability to use mathematical operations. This allows us to achieve extremely granular and accurate control with the help LESS. As an example:

1
2
3
4
5
6
.button{
    @gridUnit: 5px;
    border:@gridUnit solid #ddd;
    padding: @gridUnit * 3;
    margin: @gridUnit * 2;
}

The above code defines the variable @gridUnit as 5px.  This variable is used in 3 segments of the code but we are multiplying the margin and padding to get consistant sizes.

Operations can be multiplication, division, addition and subtraction. Sometimes you will need complex functions. Order of operations applies to these math functions as in the example below. .box will have a width equal to 200px.

1
2
3
4
.box{
    @base_unit: 10px;
    width: @base_unit(20 + 20) – 2(@base_unit + 90)
}

Color Management

Some more useful features of LESS have to do with color management. You can use math operations to modify colors. If you want to change the value of a color you can actually do so by subtracting or adding another color to it. ….. Wait what? You heard me this means we can mix colors!

1
2
3
4
5
6
@color: #941f1f;
button {
    background: #941f1f + #222222;             
    border: #941f1f - #111111;
}

The above operation in the background will increase each HEX value by 2. This results in “B64141” which is a lighter variation of the original color. The operation in the border will decrease each HEX value by 1 resulting in a darker color: “830E0E”.

Class Nesting

When writing CSS you use a cascading style. Meaning we cascade classes in a line to specify the particular elements we want to style. To change the margin of paragraphs inside blog post teasers and article page only you could use the following code.

1
2
3
4
5
6
.article.teaser p{
    margin: 0 0 12px 0;
}
.article.post p{
    margin: 0 0 12px 0;
}

There is nothing wrong with this approach but when you also want to change the links, blockquotes, headings, pre-formatted text and so on inside this same element you would need to prefix each with “.article.teaser” and “.article.post”. This makes our code more tedious to write, larger, and harder to read.

In LESS we can nest these rules, which gives a shorter and more logical version of our stylesheet. Observe.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.article{
    .teaser,
    .post {
        p{
            margin: 0 0 12px 0;
        }
        a {
            color: blue;
        }
        a:hover {
            color: green;
        }
        img {
            padding: 20px;
        }
    }
}

See what I did there? I nested an A, P, and IMG tag inside of two article classes. The tabbing is not necessary by the way but it makes it much more legible and easier to read. You can nest rules as much as you like which saves you a lot of worrying later on. Have you ever wanted to change the padding of something but were scarred because you didn’t know exactly what elements it might affect? By using nesting you can take a lot of the guesswork out of your CSS.

LESS Mixins

Mixins in LESS is not only a time saver but nothing short of organizational awesome! Have you ever created a rounded border on just the top two corners of all your elements? It is a terrible mess.

1
2
3
4
5
6
7
8
.tab {
    -webkit-border-top-left-radius: 6px;
    -webkit-border-top-right-radius: 6px;     
    -moz-border-radius-topleft: 6px;
    -moz-border-radius-topright: 6px;
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
}

You end up with the code above on EVERYTHING! With LESS you can change all that by creating a mixin. Mixins are reusable elements which you can add as a style rule to any other element. The beauty of them is that there is no additional syntax to learn. You just call the class name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.rounded_corners {
    -webkit-border-top-left-radius: 6px;
    -webkit-border-top-right-radius: 6px;
    -moz-border-radius-topleft: 6px;
    -moz-border-radius-topright: 6px;
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
}
.tab {
    background: #333;
    color:#fff;
    .rounded_corners;
}
.submit {
    .rounded_corners;
}

In the above code we defined the .rounded_corners element to have rounded corners on top. When we add this to any other element as a mixin (see .tab) we are basically importing the rules we created for it. Due to the syntax of mixins you can use any previously defined element as a mixin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.rounded_corners { 
    -webkit-border-top-left-radius: 6px;
    -webkit-border-top-right-radius: 6px;     
    -moz-border-radius-topleft: 6px;
    -moz-border-radius-topright: 6px; 
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
}
.tab {
    background: #333; 
    color:#fff;
    .rounded_corners;
}
.submit {
    .tab;     
    background: red;
}

The CSS rules for the .submit element will now call for rounded corners on top, a color of white and a background of red (the original #333 is overrided by red). Mixins can also take arguments, which are variables pass to the block of selectors when it is mixed in. These are known as parametric mixins.

Parametric Mixins

Parametric mixins sound extremely complex but they solve a problem in a very simple way. In the examples above you saw how we could define an element to have a 6px radius on its top corners. How about if we want an element to have a 3px radius? Should we declare new mixins for each new case? Of course not, we can achieve the same thing with parametric mixins.

These resemble functions because your’e not only create a mixin but you adding a variable which can be passed to it when you call it. Let’s rewrite the border radius example to take a look at how it’s done.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.rounded_corners(@radius) { 
    -webkit-border-top-left-radius: @radius;
    -webkit-border-top-right-radius: @radius; 
    -moz-border-radius-topleft: @radius;
    -moz-border-radius-topright: @radius;
    border-top-left-radius: @radius;
    border-top-right-radius: @radius;
}
.tab {
    background: #333; 
    color:#fff;
    .rounded_corners(6px);
}
.submit {
    .rounded_corners(3px);
}

The above code will give our tab element a 6px radius while our submit element will receive a radius of 3px.

Adding Default Values to your Parametric Mixin

Along those same lines, sometimes 95% of your uses will involve only one size and you have an exception. In our case let’s say everthing we use the mixin a default value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.rounded_corners(@radius:6px) {    
    -webkit-border-top-left-radius: @radius;
    -webkit-border-top-right-radius: @radius; 
    -moz-border-radius-topleft: @radius;
    -moz-border-radius-topright: @radius;
    border-top-left-radius: @radius;
    border-top-right-radius: @radius;
}
.tab {
    background: #333; 
    color:#fff;
    .rounded_corners;
}
.submit {    
    .rounded_corners(3px);
}

In this example the tab element will receive the default 6px border radius but the submit element will receive the 3px one as needed.

Importing Files and Commenting in LESS

Thankfully, just like with normal CSS you can import files. This is great for organizing sections of styles. LESS lets you import both CSS and LESS files with the following syntax with the same call you would make from CSS:

1
2
3
@import "reset.min.css";
@import "framework.less";
@import "widgets";

It is important to note, while not necessary, you should include a .extension like .css or .less to help other users know what type of file it is looking for. If you do not include an extension LESS will assume it is a .less file. So in the example above 2 and 3 would be looking .less files and 1 would be trying to load a .css file.

As expected, multi-line comments are available in LESS in the same way that they are used in CSS. In addition LESS allows for single line comments to be used just like in PHP; by using a double forward slash.

1
2
3
4
5
6
7
8
/*
    This is my main LESS file.         
    It governs how most of the site looks.
*
body {
    padding:0px; // This resets the body padding
}

Wrapping Up

While we have only just scratched the surface of what LESS can do, these simple features will help anyone working in CSS to make it not only less time consuming but easier to modify through development and past production. For LESS beginners, remember that it is just like CSS so you can slowly learn the techniques above and integrate them one at a time into your style sheets.

For further information don’t forget to look at the less website and documentation located at http://lesscss.org. I hope you enjoyed this article and come back soon for more targeted in depth looks at LESS.