Get Into LESS: the Programmable Stylesheet Language

Get Into LESS: the Programmable Stylesheet Language

Tutorial Details
  • Topic: CSS, LESS
  • Difficulty: Beginner
  • Estimated completion time: 2 hours

I don’t like CSS. Plain and simple. It makes the World go round on the web, yet the language is restrictive and hard to manage. It’s time to spruce up the language and make it more helpful by using dynamic CSS with the help of LESS.

Let me illustrate my point with an example right away. Instead of using #FF9F94 to get a dark peach color, wouldn’t it be easier to store that color value inside a variable and just use that variable? If you want to recolor your webpage you just change the value of the variable in one place and that’s that.

In other words: it would be awfully nice if we could use some programming and logic inside CSS to make it a more powerful tool. The good news is that with the help of LESS we can!


What Is LESS?

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.


How To Use 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. If you just got scared because you saw the word “compile” (I always used to) please don’t go anywhere, it is extremely easy.

Using The LESS Javascript File

First of all head down to the LESS website and grab the Javascript file. Once you have it, all you need to do is link it to your page like any other Javascript file.

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

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

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

Make sure that you link your LESS file before the Javascript file.

Once you have this setup you can paste your existing CSS code into the LESS file or just write a few new rules – it should work just like plain ol’ CSS.

Compiling The LESS File

While this is a bit more tedious, in some scenarios this is preferred. LESS works by taking all the LESS code you write and converting it to CSS on the fly. Instead of doing this on demand we can convert our LESS file, save the CSS output and use that instead of doing the on-demand conversion on each page load.

If you’re a Mac user you can use LESS.app, a small 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.

If you’re on Windows you can use Winless which works in much the same way.

If you prefer command-line tools you can use the Node Package Manager (NPM) to install LESS. Some documentation is available on the LESS website. You can also grab the code directly from the Github repository.


Harnessing The Power Of LESS

Finally, let’s get started with the fun bit – writing LESS code. As you will see it is very easy to read and understand; it uses the same syntax style as CSS does so it should all be familiar to you.

Variables

Variables in LESS work exactly like they do in PHP or most other programming languages. You can use them to store a value and then use the variable instead of the value itself whenever you need it.

@header-font: Georgia;
h1, h2, h3, h4 {
	font-family: @header-font;
}
.large {
	font-family:@header-font;
}

In the example above we defined the @header-font variable and assigned the value “Georgia” to it. We can now use this variable whenever we want to use the Georgia font. If we decide we’d rather go with Trebuchet MS 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) I used to do something like this:

/*
 Colors for my Website
 	#ff9900 - Orange - used for links and highlighted items
    #cccccc - Light Gray - used for borders
    #333333 - Dark Black - Used for dark backgrounds and heading text color
    #454545 - Mid Black - Used for general text color
*/
body {
	background: #333333;
	color: #454545;
}
a {
	color:#ff9900;
}
h1, h2, h3, h4, h5, h6 {
	color: #333333;
}

There is nothing wrong with documenting your colors like this, it is good practice, the problem is that since it has nothing to do with the functionality of your stylesheet it has no other use than documentation itself. If you decide on a different color after line 2,000 and then change your mind at line 3,567 it will be extremely difficult to ensure the right colors are used and the documentation is correct as well.

With LESS we can modify our workflow and actually use our “documentation” instead of it remaining a passive bystander in the process.

/* Colors for my Website */
@color-orange: #ff9900;
@color-gray_light: #cccccc;
@color-black_dark: #333333;
@color-black_medium: #454545;
body {
	background: @color-black_dark;
	color: @color-black_medium;
}
a {
	color:@color-orange;
}
h1, h2, h3, h4, h5, h6 {
	color: @color-black_dark;
}

Variable Scope

The scope of a variable refers to the places where it is available. If you define a variable at the very start of your LESS file it will be available to any code you write after it.

You can also define a variable inside a CSS rule. In this case the variable is not available outside of this ruleset; it can only be used locally.

a {
	@color: #ff9900;
	color:@color;
}
button {
	background: @color;
}

In the example above the LESS file will not be converted since there is an error, @color is not defined for use inside the button element. If a variable is defined outside of an element and inside of an element the local definition takes presidence.

@color: #222222;
a {
	@color: #ffffff;
	color:@color;
}
button {
	background: @color;
}

In the example above the link will be colored white, the button will have a black background.

Variable Variables

If you’re used to coding in PHP you know that you can define a variable name with another variable.

@color-chirstmas_red: #941f1f;
@name-of-color: "color-chirstmas_red";
color: @@name-of-color;
To me personally this is of less use (no pun intended) since the power of variable variables diminishes without the use of loops but I’m sure there are some clever examples out there utilizing this.

Contants VS Variables

An important thing to note is that contrary to what you just read, variables in LESS are more like constants. This means that they can only be defined once – as opposed to variables which can be defined as many times as you’d like.

Operations

You can achieve extremely granular and accurate control with the help of operations in LESS. The idea behind this is simple:

.button{
	@unit: 3px;
	border:@unit solid #ddd;
	padding: @unit * 3;
	margin: @unit * 2;
}

The above code defines a the variable @unit as 3px. It then goes on to define the border as having exactly that width, the padding to have three times that width and the margin as having twice that width.

Operations can be multiplication, division, addition and subtraction. To create a box with a border that is increasingly wide as you move clockwise along its perimeter you can use the following code.

.box{
	@base_unit: 1px;
	border: @base_unit @base_unit + 1 @base_unit + 2 @base_unit + 3
}

Color Management

My favorite features of LESS have to do with color management. You can use operations to mix colors and there are some specific color functions.

Color Operations

If you want to change the value of a color you can do so by subtracting or adding another color to it.

@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”.

In practice there are quite a few cases where we start out with a base color and need a slightly darkened or lightened version.

@color-button: #d24444;
input.submit {
	color:#fff;
	background:@color-button;
	border:1px solid @color-button - #222;
	padding:5px 12px;
}

This creates a red button which has a slightly darker border. This is something you may need very often and not having to define the border color separately is great help.

The power of variables is even more obvious here. If you want to recolor the website and change the @color-button value to a green color not only does the background of the button change but the border also changes and becomes a deeper version of the green color.

Another great use of this is creating gradients. I typically choose a mid-point color and define the gradient from there. I make the start slightly lighter and the end slightly darker. This results in a nice transition, something like this:

@color: #faa51a;
.button {
	background: -webkit-gradient(linear, left top, left bottom, from(@color + #151515), to(@color - #151515));
	background: -moz-linear-gradient(top,  @color + #151515,  @color - #151515);
}

Color Functions

There is a lot more that you can do with colors; LESS allows you to manipulate them on a channel level. You can lighten, darken, saturate, desaturate, fade in, fade out and spin colors. Take a look at the following examples and images to see what each of these do.

@color: #3d82d1;
.left_box {
	background:lighten(@color, 20%);
}
.right_box {
	background:darken(@color, 20%);
}
@color: #3d82d1;.left_box {
	background: desaturate(@color, 18%);
}
.middle_box {
	background: @color;
}
.right_box {
	background: saturate(@color, 18%);
}
@color: #3d82d1;.left_box {
	background: spin(@color, 25%);
}
.middle_box {
	background: @color;
}
.right_box {
	background: spin(@color, -25%);
}

Extracting Color Information

Each color in LESS is converted to HSL (hue, saturation, lightness) to enable you to manage them on the channel level. Due to this you can manipulate colors in a more sensible way and also access the channel information of a color directly:

@color = #167e8a;
hue(@color);
saturation(@color);
lightness(@color);

This might seem like micromanagement – why do we need this information when we can just enter a HEX value? If you’re like most people HEX values don’t come naturally to you. HEX values map the RGB spectrum. the first two characters controlling the amount of red, the next two the amount of green and the last two the amount of blue.

It is fairly obvious that #ff0000 is red since this would be RGB(255,0,0). Tons of red, no green and no blue. However, if you just see #1f6b2d it is hard to decypher that this is a deep green. With a HSL scale the hue controls what you would call color, the rest just sets the tone (this is not exactly right, but for all intents and purposes it is).

With that in mind if you found a nice magenta-purple color like #e147d4 you can find a different color with the exact same hue very easily. Say you want to create a creamier, more pastel version of #e147d4, here’s what you can do:

@color: #e147d4;
@new_color: hsl(hue(@color), 35%, 77%);

This new color will have the same hue but a different saturation and brightness. The result will be #c480bf which is quite difficult to arrive to from #e147d4 if you’re just thinking in HEX.

Combining Funtions

LESS allows you to use functions inside functions, so if you want to desaturate and spin a color you can do that in a jiffy like so:

@color: #c480bd;
.class {
	background-color: desaturate(spin(@color, 18), 12%);}

Nesting

When writing CSS you use a cascading style. To change the margin of paragraphs inside blog posts only you could use the following code.

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.post”. This makes our code more tedious to write and harder to read.

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

article.post {
	p{
		margin: 0 0 12px 0;
	}
	a {
		color: red;
	}
	a:hover {
		color: blue;
	}
	img {
		float:left;
	}
}

See what I did there? The tabbing is not necessary by the way but it makes it much more legible. 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.

a {
	color:red;
}
p {
	margin:0px;
}
article {
	a {
		color: green;
	}
	p {
		color: #555;
		a {
			color:blue;
		}
	}
}

Mixins

Mixins in LESS is the feature which will save you the most typing. have you ever created a rounded border where only the top left and right corners were rounded?

.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;
}

Uggh… Each and every time… With LESS you can change all that by creating a mixin. Mixins are reusable elements which you can add as a rule to any other element. The beauty of them is that there is no additional syntax to learn.

.rounded_top {
	-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_top;
}
.submit {
	.rounded_top;
}

In the above code we defined the .rounded_top 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 old element as a mixin.

.rounded_top {
	-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_top;
}
.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 orinal #333 is
overwritten).

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 separate mixins for all pixel values? The answer is of course not, we should use parametric mixins!

These resemble functions because you not only create a mixin but you can pass values to it when you call it. Let’s rewrite the border radius example to take a look at how it’s done.

.rounded_top(@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_top(6px);
}
.submit {
	.rounded_top(3px);
}

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

Default Values

If you usually use the same border radius but in some cases you need a different one you can give the mixin a default value.

.rounded_top(@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_top;
}
.submit {
	.rounded_top(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.

Multiple Parameters

You can also use multiple parameters to define more complex mixins.

.radius(@radius:6px) {
	-webkit-border-radius: @radius;
	-moz-border-radius: @radius;
	border-radius: @radius;
}
.button(@radius:3px, @background: #e7ba64, @padding: 4px) {
	.radius(@radius);
	background:@background;
	border: 1px solid @background - #222;
	padding: @padding;
}
.read_more {
	.button(0px);
}

Whenever you create an element with the .read_more class using the example above it will format it with a 4px padding, the background color of #e7ba64 and
with a 0px border radius.

Using All Arguments At Once

One more option you have when using arguments is to use the whole lot all at once. Shorthand properties in CSS have multiple values written one after the other.

div {
	border:1px solid #bbb;
}

You could use a function to give all required elements a gray border like so:

.gray_border(@width: 1px, @type: solid, @color: #bbb){
	border:@arguments;
}
div {
	.gray_border(2px, dashed);
}

The @arguments is a special keyword, it will output all parameters one after the other in the order given. In the above case the CSS code resulting from
your LESS file would be:

div {
	border:2px dashed #bbb;
}
Parametric Mixins Without Paremeters

It is also possible to use parametric mixins without actually using any parameters. This is used when you do not** want the mixin to show up in your CSS code but you **do want its rules applied to the elements it is used in.

.alert {
	background: red;
	color: white;
	padding:5px 12px;
}
.error_message {
	.alert;
	margin: 0 0 12px 0;
}

The CSS output of the above would be the following:

.alert {
	background: red;
	color: white;
	padding:5px 12px;
}
.error_message {
	background: red;
	color: white;
	padding:5px 12px;
	margin: 0 0 12px 0;
}

If you use an empty parameter set you can hide the .alert class.

.alert() {
	background: red;
	color: white;
	padding:5px 12px;
}
.error_message {
	.alert;
	margin: 0 0 12px 0;
}

The CSS produced from the above LESS code would be:

.error_message {
	background: red;
	color: white;
	padding:5px 12px;
	margin: 0 0 12px 0;
}

This is primarily useful for cutting down the size of your CSS file. If the .alert class is never used directly on any element there is no reason to have it in the resulting stylesheet as long as its properties are passed along to the needed elements as mixins.

Namespaces

Namespaces in programming languages are typically used to group packages of functionality together. We can achieve the same in LESS by bundling our code using mixins.

#my_framework {
	p {
		margin: 12px 0;
	}
	a {
		color:blue;
		text-decoration: none;
	}
	.submit {
		background: red;
		color: white;
		padding:5px 12px;
	}
}

When starting work on a new website based on your framework you can add this #my_framework bundle and use it without messing up any other styles you might already have or want to add in the future.

.submit_button {
	#my_framework > .submit;
}

This is also a great way to enable quick theme changing and modification. If you develop a number of themes for your company to use as templates on demand you can include all of them as bundles in the same LESS file and use use the one you need.

#fw_1 {
	p {
		margin: 12px 0;
	}
	a {
		color:blue;
		text-decoration: none;
	}
	.submit {
		background: red;
		color: white;
		padding:5px 12px;
	}
}
#fw_2 {
	p {
		margin: 8px 0;
	}
	a {
		color:red;
		text-decoration: underline;
	}
	.submit {
		background: blue;
		color: white;
		padding:8px 20px;
	}
}
.submit_button {
	#fw_2 > .submit;
}

String Interpolation

String interpolation is just a fancy word which means that arbitrary strings can be stored in variables and then used inside property values.

@url: "http://mycompany.com/assets/";background-image: url("@{url}/sprite.png");

The above can be immensely helpful when creating centralized frameworks and making sure that resources are pulled from the correct place.

Escaping

In some cases you will need to use properties or values which are not valid CSS (IE rules anybody?). You may have noticed in our gradient example that I did not cater for Internet Explorer users.

If you want to create a gradient in IE you will need to do something like this:

filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#666666', endColorstr='#444444');

The above is not valid CSS so the LESS processing will not be able to complete. In this case you can escape this value which will make LESS skip it and move on. The result of this is that it will be output to your CSS without any processing.

.button {
	background: -webkit-gradient(linear, left top, left bottom, from(#666666), to(#444444));
	background: -moz-linear-gradient(top,  #666666,  @color - #444444);
	filter:  ~"progid:DXImageTransform.Microsoft.gradient(startColorstr='#666666', endColorstr='#444444')";}

All you need to do is encase the section in quotes and tack a tilde character in front of it. This section will not go through the LESS processor so will not throw it off.

Importing

Just like with normal CSS you can import files. LESS lets you import both CSS and LESS files with the following syntax:

@import "reset.min.css";
@import "framework.less";
@import "widgets";

The first import is pretty obvious. This will import the CSS rules defined in reset.min.css without running them through the LESS parser.

The second import will pull the contents of framework.less and process them just like any other LESS rules.

The third import is essentially the same as the second. If an extension is not given LESS presumes it to be a LESS file.

Comments

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.

/*
	This is my main LESS file.
	It governs how most of the site looks.
/*
body {
	padding:0px; // This resets the body padding
}

What’s Missing?

While LESS is awesome you will find some shortcomings when you start using it although these are not very bothersome. One feature I’d love to see is pre-pre-processing (I agree, this makes no sense).

Remember how lines can be escaped so that they don’t run through the parser? Due to the current way LESS handles things we can’t really use gradients with variable color names.

	filter:  ~"progid:DXImageTransform.Microsoft.gradient(startColorstr='#faa51a', endColorstr='#f47a20')";

The above works just fine but the colors have to be hard coded in. Since the line is escaped, variables aren’t processed. It would be nice to have an option where the indicated string is escaped but variables are processed before the output is sent to the CSS file.

Another feature I would like to see implemented is variable naming of selectors and other elements, not just values. When we were looking at namespaces we used something like the following to add rules.

a {
	#my_framework > .link
}

It would be great if we could do this something like this instead:

@framework: "#my_framework";
a {
	@{framework} > .link
}

This would enable me to add all my frameworks to a single LESS file and then choose one by simply changing the value of the variable.

There are very few bugs and a couple of other shortcomings but overall LESS is very usable and very stable.


Conclusion

As with all new technology and methodology there is an urge to over-use. Remember reflective logos at the beginning of the Web 2.0 era?

You don’t have to nest all your rules, you don’t have to create variables for everything and mixins for a simple border width.

If you don’t know when not to use the awesome power of LESS your LESS code will be come just as unreadable as regular CSS and just as hard to maintain. The trick is to know when to utilize the given functions and methods and when regular old CSS is best.

In addition I suggest not using LESS in production. There is nothing wrong with it but there’s simply no reason to load a LESS file and a script to process it. Apparently the script is very quick but I’m sure it isn’t quicker than not having it there. I usually develop all my websites with LESS and when I’m happy I just grab the output, minify it and use it in a regular CSS file.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.ait-themes.com/ Ait-Themes.com

    Thanks for the article. We use Less in all our recent themes. Cannot image doing WordPress themes without Less now ;)

  • http://www.szek.net andi

    thanks, this is a much needed and awaited tutorial. i haven`t had the courage to start coding with LESS yet…but it`s time now:)

    regards,
    andi

    • http://www.menacedesign.pl Artbeard

      Same here;)

  • http://www.southmakers.com Alvaro

    Been working with LESS a lot lately, and this is one of the most useful tools I ever found, it reduces the interface development time considerably, maybe you cannot feel the difference in small web projects, is in large projects where you can actually see all its power.

    Maybe this is the first step to Object Oriented Style sheets?

  • Thomas

    There is also a less.php script to convert your less files server-side on demand. If you build your websites with PHP, this is the best way to go :)
    http://leafo.net/lessphp/

    • http://danielpataki.com Daniel
      Author

      Hi Thomas,

      I’m not a big fan of on-demand conversions, I think they are only useful in a development environment (although they are awesome there). Once you’ve completed your coding there is really no need to convert the same less file to the same css every single time.

      It’s better to just compile the thing into css once and then only touch it if you want a design change. Just switch back to on-demand conversion, make your changes until you’re happy and then compile again and go back to normal css.

  • http://kontrary.com Rebecca

    This looks awesome. I can’t wait to try it out – thanks for the super-detailed tutorial! So helpful.

  • http://georgeohler.com George

    I’d also like to mention the powerful parent selector ‘&’ inside of LESS. The parent selector also got a recent update, where I can think the best use of it is when I am doing IE (or other browser) compatability.

    The parent selector is very powerful in the idea that you can easily pull the entire chain of selectors out of a nested declaration, but it’s also useful for other things, especially psuedo selectors, but can be utilized for class or ID chaining as well. Example:

    Nested LESS:

    body {
        background:black;
        a {
            color:white;
            &:hover {
                color:yellow;
                .internet-explorer }
        }
    }
    

    Will output this CSS:

    body { background: black; }
    body a { color: white; }
    body a:hover { color:yellow; }
    .internet-explorer body a:hover { color: blue; }
    

    LESS is amazing, and while there are avid SCSS users out there too, I’ve always preferred LESS. The new integration of the methods found in LESS and SCSS into the new CSS draft is interesting, but they’re definitely taking their own stand on the syntax. I don’t quite understand this as LESS and SCSS are very similar and many people are already very familiar with them, but all in all they’re already greatly influencing how we use CSS.

    • http://danielpataki.com Daniel Pataki
      Author

      George I did NOT know that and I’ve been thinking how awesome this would be. If you have a huge set of rules it’s so weird putting the hover and active state AFTER it because it gets kind of lost. Thanks for your addition!

      • http://georgeohler.com George

        No sweat, the code didn’t translate very well via the comment system, but this is a great discussion of what eventually got implemented by Alexis: https://github.com/cloudhead/less.js/issues/9

        • http://www.snaptin.com Ian Yates

          Thanks for your input George – I’ve tidied up the code in your comment to help clarify things :)

          • http://georgeohler.com George

            If you don’t mind fixing the last few lines of the less that reads:

            .internet-explorer }
            }
            }

            should be
            .internet-explorer (of course correct closing brackets for the nests should be still included)

            Might’ve just had a brain fart when I wrote it the first time.

    • Mark Rivera

      haha… maybe he’s drunk when he code this. >.<
      However, Less is cool… Thanks for the article Dan!

  • http://www.forwart.be/ for-w-art

    Looks promising although I found the code in the examples they’re giving to be somewhat longer.
    Still it’s a wonderful idea and one the things even I thought off that would or could make my life a lot easier.

  • http://www.nurakanbpo.com Kanchan Rai

    When I was developing my Company’s website, I came through an article talking about LESS and SCSS, and I visited both the sites. I preferred LESS, downloaded some videos and implemented in my website. That was my first experience with LESS and using it was fun although I mostly used mixins and nested CSS and sadly the top part of my CSS is still plain CSS.

    Anyways, I’m just excited to explore LESS CSS more and more and here you go, just the thing I was looking for. Although, I’m still new to LESS, I have already used it and enjoyed using it, the flexibility if offers, I recommend implementing it immediately so that we can push CSS to be more logical like CSS3 has evolved. For a very huge site with lots of CSS, LESS is a boon! It reduces the CSS codes by more than half man! Just amazing!

    I would love to have a video tutorial for LESS as well, showing the implementation of LESS on styling a full website. That would be amazing, a deeper insight and practical implementation. Thanks a lot!

    • http://www.nurakanbpo.com Kanchan Rai

      Forget to give my Website’s link :
      You can visit it here, it’s still undergoing construction BTW!
      http://www.nurakanbpo.com

      and yeah I have used LESS CSS and I’m happy!!

  • Mike

    Less is amazing..It actually helps in the understanding of CSS as well as far as the way CSS “Cascades” ..The biggest issue I find with less is that where it’s GREAT in the development of a website it’s best to use the compiler before going live or putting your website into production status. I’ve read articles about it but basicly the extra work that JS is doing to convert the .less to a standards compliant and working .css for the web browser to interpret is bandwidth and time that user’s are not viewing your website…On a small website that doesn’t get many views daily this isn’t an issue but a website like say tutsplus.com or facebook or twitter using less will rack up some serious compile times when it comes to utilizing less. SO..Yes less is more and it’s an amazing workflow when designing but once the design is done it’s best to compile and use straight CSS on your production site. Just my two cents :)

    • http://www.snaptin.com Ian Yates

      Thanks for that Mike, and thanks for drawing the comparison between tutsplus.com’s traffic and facebook’s :)

    • techeese

      does that mean less makes production sites slower? because of the JS? although it lessens the CSS?
      am I understanding that, right?

      • http://twitter.com/drale2k Drazen Mokic

        Yes, but only if you use the less.js script to “translate” less into css on the fly. So while developing the less.js is really great since you don`t need to compile less to css everytime you save or use some command line –watch command like in SASS, but once you go in production just compile your less to css and you are ok.

        If you want a great tool which compiles less and does other great stuff, check out Codekit http://incident57.com/codekit/

      • http://danielpataki.com Daniel Pataki
        Author

        Yes, but on production sites you definitely won’t notice this. Most of the trouble comes from loading the external resource (the JS file). Since the conversion is done by your own computer it IS pretty fast.

  • Danilo Celic

    Thanks for the in-depth article on working with LESS. I’ve been wanting to get more into LESS, SASS, or Stylus for many of the features that you’ve outlined above. I see these tools as quite helpful in quickly putting together future sites with a minimum of CSS authoring.

    A few issues I noticed:
    1. In the variable section you use color names that you’re using for the values as part of the variable names in an effort to “use your documentation”. That seems like a poor practice to advocate. If you ever change the colors, you’ll have to change the variable names too. Which means you’re giving up the point of using variables: change values without changing references throughout your code.

    2. In the String interpolation section, the generated URL appears that it will have doubled up the / that will be between the base URL and the file name.

    3. In the Comments section, the ending token for the multi-line comment is reversed. Currently /* should be */

  • Martin

    this is what i was looking for :) amazing , thanks for article :)

  • Gavin Elster

    Daniel, you can definitely use variables in escaped strings, I actually use some for the exact use case you mentioned! (You have to use the @{variable} syntax when they’re in strings) Very useful for dealing with IE oddities…

    Example:

    filter: ~"progid:DXImageTransform.Microsoft.gradient( startColorstr='@{startColor}', endColorstr='@{endColor}',GradientType=0 )";
  • http://webtechnikak.hu Festo

    Hi!

    I offer a SimpLESS to compiling the LESS files:
    http://wearekiss.com/simpless

    It is works on all major OS.

  • Pingback: Get Into LESS: the Programmable Stylesheet Language | Shadowtek | Hosting and Design Solutions

  • Anh Vu

    Hi, I have been learning Ethan Marcotte’s responsive design for the past few weeks and I really want to implement it on my website, but one shortcoming is that I can’t get respond.js (polyfill for IE8 and below for media queries) to work together with LESS. Is there any trick to get them play nicely together?

  • Brad

    I love LESS, but I don’t have to compile anything. Just link to the js file and let it do the work. But I agree you wouldn’t use it on a large site like Nettuts

    I use it in conjunction with HTML5 boilerplate, turning that CSS file into a LESS file.

  • http://www.marcusmcnamara.com Marcus

    I believe you are mistaken in that you cant use variables for a gradient mixin due to having to escape the IE gradient filter… this is not true, at least for the .net version of less (dotLess)

    Below is my code, which i guarantee works and is currently in our production environment

    Enjoy, and hit me up on twitter if you find this useful @marcusmcnamara

    .gradient(@color_start: #000000, @color_end: #ffffff) {
    	background: @color_start; // Old browsers
    	background: -moz-linear-gradient(top, @color_start 0%, @color_end 100%); // FF3.6+
    	background: -webkit-linear-gradient(top, @color_start 0%,@color_end 100%); // Chrome10+,Safari5.1+
    	background: -o-linear-gradient(top, @color_start 0%,@color_end 100%); // Opera11.10+
    	background: -ms-linear-gradient(top, @color_start 0%,@color_end 100%); // IE10+
    	background: linear-gradient(top, @color_start 0%,@color_end 100%); // W3C
    	filter: formatstring("progid:DXImageTransform.Microsoft.gradient(startColorstr='{0}', endColorstr='{1}', GradientType=0)", @color_start, @color_end); // IE6-9
     }
    
  • http://www.datatrac.co.za Randy

    i feel like i have been living under a rock. havent heard of LESS… life changing indeed. Definitely getting into this ASAP

  • https://twitter.com/#!/shanejfullwood Shane

    Less really is sweet. I had been watching it since last year or before but recently the popularity is amazing. We have the likes of @malarkey (Andy Clarke) apologising for saying “I once wrote that there was no need to use a CSS pre-processor like LESS or Sass. I was wrong. Very sorry.”. He now includes his LESS files in his mobile first framework, 320 and Up.

    Then there are the various frameworks popping up that use less such as, Twitter Bootstrap produced by a bunch of chaps from Twitter. It is currently at version 1.4 and is not responsive but V.2 is expected in the not too distant future and will be responsive.

    Also check out Semantic.gs which does away with the need for grid classes like span_1 etc.

    Responsive LESS Boilerplate is rather nice and is based on <a href="http://html5boilerplate.com/"HTML5 Boilerplate, Semantic.gs and of course, LESS.

    If you use a Mac, then there are a few apps that compile the less files for you and output a relatively named css file. LESS.app and Codekit are from the same developer but LESS.app was released first and only compiles LESS where as Codekit is rather new and is still in beta and will be a paid app once a full version. Codekit is special, it compiles LESS, SASS, Stylus, HAML and Coffee Scrip. It can also combine, minify and error check JS. It even optimizes images, auto-reloads your browser and lets you use the same files across many projects.

    Phew. Hope this info will help those interested in getting started with LESS. Check out the frameworks, see how they work and enjoy.

  • Ivan

    I totally got my mind blown.

    A new era begins!

    • http://danielpataki.com Daniel Pataki
      Author

      Exactly how I felt when I found out about it!

  • eeean

    I don’t think LESS is a good idea.

    1. Compilation adds unnecessary complexity. It adds a step to development and it destroys the pervasive accessibility and simplicity of CSS in the first place.

    1. Compilation introduces another layer of technology which can go wrong. JS or PHP or application compilers now have to be kept up to date and working, and available in order to make changes (as opposed to just opening a plain text file to make edits).

    2. It increases the complexity of a stylesheet, and decreases the readability by introducing new syntax. It means anyone who needs to work on the style infrastructure of a site needs to have yet another technology under their belt.

    3. It abstracts the cascade. Most web developers don’t actually write efficient class based cascading styles to begin with, using too many ID’s (repeating element definitions) and ignoring the flexibility and cascading modularity of classes. As a result, LESS is like learning to run before you can walk.

    4. It adds yet another file, yet another HTTP request and yet more CPU load, and introduces potential compatibility risks to the client-side.

    I’m not saying it’s not useful, I’m just saying that if you are using it chances are you aren’t writing good enough CSS to begin with. Yes this is a big generalisation, but I think that LESS and other similar technologies introduce added complexity where it isn’t required.

    • Heidi

      You are allowed to your opinions, but your comments are floating and to avoid readers to get misguided, I’d like to add my view and more texts to some of your bullets.

      #1 compilation is not needed.

      #2 I don’t agree that it increases the complexity of a stylesheet. The extra syntax is simple and very intuitive for a programmer (subtracting etc. isn’t too hard to understand).

      We have huge CSS files and LESS could certainly be very usefull in that case.
      We have several people working on the CSS files simultanously (not the exact same parts though) and LESS can increase the overview for the single person plus avoid some of the usual ‘bugs’ to show up, where a person didn’t have time to read ALL dependencies before altering a style.

      #3 When you are working on big systems you HAVE to write efficient classes from the beginning – or at least get there very fast. And yes – I agree, you DO have to learn basic CSS before you can use LESS properly.

      #4 CPU load: Not an overload worth mentioning compared to the huge stylesheets filled with unnecessary/not-used styling I sometimes see.
      But yes, whenever you add extra functionality there is one more place for errors to pop up.

      I agree you should choose wisely when to use LESS and when not to. But simply refuse to use LESS in all cases or claim that LESS users are mostly very bad CSS writers is a very arrogant attitude.

  • http://www.justinhubbard.me Justin Hubbard

    IMO, this is highly inconvenient when working with CSS. It’s just as easy, if not easier to use #FFFFFF instead of a variable, plus your just adding more unnecessary bloat. I suppose for some who are more comfortable with javascript or php that the idea of variables would come more naturally, but since HTML and CSS were the first codes I learned to write, it’s definitely inherently easier to just use them as is and still produce the same results with less bloat than you would with the help of javascript.

    Just my 2c

    • eeean

      Agreed, which is exactly why find and replace a colour is just as effective and more familiar than a variable.

      • maulik13

        If you have 4 variants of blue in a button and want to change blue button to green, you have to replace colors 4 times. Using LESS’s color functions, it’s just one change in a single place.

  • http://gadgetsection.dk Teknologinyheder

    What is the main difference between SASS and LESS?

  • sun

    Hi. That ist an extremly cool article! Less makes so many Thinks easier in the world of css. Thanks!

  • http://smartpapers.tk Mehdi Raza

    Is there any way to throw a javascript expression’s output (which is a series of classes) into the CSS?
    For example, i want to output:

    .grid_1 { .grd(1); } .grid_2 { .grd(2); } .grid_3 { .grd(3); } .grid_4 { .grd(4); } .grid_5 { .grd(5); } .grid_6 { .grd(6); } .grid_7 { .grd(7); } .grid_8 { .grd(8); } .grid_9 { .grd(9); } .grid_10 { .grd(10); } .grid_11 { .grd(11); } .grid_12 { .grd(12); }
    

    ……using:

    `(function(b){var a="";for(i=1;i<b;i++)a+=".grid_"+i+" { .grd("+i+"); }\n";return a})(12)`;
    

    Expanded form of the js:

    (function(columns){
          var out='';
          for(i=1;i<columns+1;i++){
            out+=".grid_"+i+" { .grd("+i+"); }\n";
          }
          return out;
        })(12);
    
  • http://tenterfields.net Tenterfields

    I have to admit, as I read through this article I found myself questioning whether these techniques necessarily represent a huge step forward in convenience or versatility. Perhaps I am missing the point somewhere, but I felt like I could achieve the same results with standard CSS, just by using a different approach.

    The Mixins for example… Could somebody explain why it is better to define a variable and then insert it into CSS classes? I mean, isn’t it cleaner just to define a class then add it to whichever HTML elements you choose? They seem like exactly the same thing to me, the only difference is that Mixins apply it to CSS elements and standard CSS would apply it through a tag in the HTML.

    • eeean

      Yes, you are correct. See my comments above. LESS is an interesting tool, but if you can’t write great CSS to begin with it’s probably distracting you from ever getting any better at it.

  • Aarron

    Mark Otto has some great mixin’s that you can use over at preboot.less:
    http://markdotto.com/bootstrap/

    …most of which have been incorporated into Twitters Boostrap:
    http://twitter.github.com/bootstrap/#less

  • arnold

    so without javascript , it will not work …

    we have ‘Find and Replace’ in every text editors , its not that hard to replace some single code in your CSS…

  • http://www.dhaneshtk.com dini

    Just makes things more complicated….
    Its an age old concept- the more sophisticated…the more superior…
    Now its the age of simplicity…

  • http://magnumdesign.zzl.org/ Matheus Mariano

    I think the Less a very nice framework, but I prefer use the jQuery to make a programmable stylesheet.

  • Pingback: The WFL Weekly Round-Up ‹ Worry Free Labs Blog

  • AntoxaGray

    I remember I tried to use it once, sometimes it wouldn’t generate CSS, had to F5 page. I used wordpress.

  • Pingback: Best of Tuts+ in December 2011 | Inspirations, dreams, humaniora

  • Pingback: Best of Tuts+ in December 2011 |

  • Pingback: My Stream » Best of Tuts+ in December 2011

  • Pingback: Best of Tuts+ in December 2011 | linuxin.ro

  • Pingback: Best of Tuts+ in December 2011 | Shadowtek | Hosting and Design Solutions

  • Pingback: Best of Tuts+ in December 2011 | clickshots

  • http://www.twitter.com/tjbarber09 T.J. Barber

    I disagree with those saying that LESS is too complex to use. It does add another layer, but it streamlines your work and makes it more fun to code if you have experience with Ruby or another programming language.

    I love being able to use variables in CSS just like I do in Ruby, and if a CSS coder can’t understand what’s being said then he/she needs to go get some experience in object-oriented programming. It’s really not hard. Go play with a simple Ruby tutorial and this will all make sense to you. Hey, if you code at least some JavaScript then it should be even better. You’ll completely understand LESS.

    As for it not generating, I would not use LESS in a final website. I would take my LESS code, run it through the compiler, minify it, and stick it in my site as standard CSS. You check out LESS.app for Mac, because it will make this stuff really simple.

  • http://matthewdean.me/ Matthew

    Have you tried Crunch? As far as I know, it’s the only GUI editor for LESS, and compiles down to CSS. Great alternative to Winless or Less.app.

    http://crunchapp.net/

  • Pingback: Best of Tuts+ in December 2011 | Graphfucker

  • http://www.nomad-one.com nomadone

    I’m so intrigued by LESS, and yet never actually used it, though I hope to give it a bash soon. I haven’t however found much covering it’s use with WordPress themes, and was wondering if anyone has experience using LESS in combination with theme options to allow theme users to quickly and easily restyle their themes.

    Would take flexible restylable themes to the next level I think, especially with some of the color management and mixing examples I’ve seen.

  • Pingback: Best of Tuts+ in December 2011 « Fast Ninja Blog by Freelanceful – Web Design | Coding | Freelancing

  • Pingback: Best of Tuts+ in December 2011 | Wptuts+

  • http://www.kreativeking.com Clemente – Kreative

    Am I the only person who thinks Media Queries kind of make this useless?? Moving forward atleast.

  • Pingback: Weekly Roundup @ WPKewl – January 9th-15th 2012 - WPKewl! - WPKewl!

  • Pingback: Best of Tuts+ in December 2011 | HowDoDesign

  • http://www.themenzclub.net Mack Hankins

    This looks like something I need to try.

  • Pingback: Hello world! | lightware Technologies Hello world! | Web Designing

  • Maciej

    I think there is a urgent need in the CSS world for loops through -moz-…, -webkit-… etc. so you can just put something like @[border-radius]: 3px and you are good to go :)

  • Pingback: UX@UW | Cleanup Your CSS Mess with LESS

  • Pingback: {less}, the Dynamic Stylesheet Language ‹ Miren Berasategi

  • Pingback: Practical Tips For Using LESS | Webdesigntuts+

  • http://xvelopers.com Nauman

    That’s really helpful i am planning to use it in my next project. Thanks for nice tut

  • Pingback: LESS overview | blog.dsetia.com

  • Pingback: CSS Metasprache – Do more with Less › Digital Native

  • Pingback: 7 Ways to Code Faster HTML CSS | Problemnsoution

  • Tomz

    Thank you for your good articles..
    I’m learning with the series (adaptive-blog-theme-from-photoshop-to-wordpress) So excited!
    Crystal Clear :)

  • Pingback: Ultimate super basic introduction to LESS : Point At The Moon

  • Pingback: Writing CSS with LESS by Jay Fallon | Web Development

  • Pingback: A bit of responsiveness for WooCommerce 2.0 default stylesheet - Nomine Web Creations

  • Pingback: Best of Tuts+ in December 2011 | Envato Notes

  • Pingback: Get Into LESS: the Programmable Stylesheet Language | Webdesigntuts+ | Gristech

  • Pingback: LESS ile daha az CSS | Ozengen

  • Pingback: On Writing CSS - Signal Tower