Learning Less.js

By Alex Libby
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introducing Less

About this book

Writing CSS styles can be very tedious–how many times have you written CSS styles that become difficult to read and manage, and frequently have to be duplicated? Less gives you a solid toolkit that can help streamline your code when developing styles for any website of any size, with a significant reduction in the amount of time and effort required.

Learning Less.js helps you maximize your experience with the Less library by breaking down each of its main features. This book walks you through examples that progressively build upon your knowledge, taking you from beginner to advanced usage in a series of easy-to-follow steps. We begin with exploring the library, and will learn about the tricks it uses to help us save development time when creating and managing styles, right through to using Less.js in some practical, real-world scenarios.

Publication date:
October 2014


Chapter 1. Introducing Less

Are you tired of writing the same old CSS styles for client websites only to find out that you're repeating yourself? Wish you could cut down on what you write and still produce the same results…?

Well, you can. Welcome to the world of CSS preprocessors, and in particular, Less! CSS preprocessors such as Less are designed to help you reorganize your styles to smaller, more manageable chunks of reusable code that you can store and reference as and when your projects demand.

Less, designed as a superset or extension of CSS, is very much about making your development work easier—it incorporates variables and functions that are more likely to be seen in scripting languages such as JavaScript while still compiling in valid CSS. While the initial thought of working with code might scare you, you'll see that Less is really just CSS, but with some additions to help make development easier. Less will help you cut down the development time, as you can reuse code from one project in another—how much is all up to you!

In this chapter, we will cover the following topics:

  • The roles of HTML and CSS, and the limitations of using CSS

  • Why CSS preprocessors are needed

  • Why you should use Less

  • The advent of CSS4, and what this means for Less


The role of HTML and CSS

If you spend time developing websites for clients, it is likely that you will have used both HTML and CSS to create your masterpiece.

HTML, created in 1990, has been the de facto standard for placing content on a web page. Over the years, it has evolved into what we now know as HTML5, which we can use to produce some very detailed websites or online applications. To use a cooking analogy, HTML is effectively the creation of the cake base; it is content that makes sense to any Internet browser. HTML forms the base of any website available on the Internet—it won't look very exciting, but it will have all the elements you need, such as headings, paragraphs, and images, to produce well-formed pages. Well-formed pages are made up of two elements: accessibility and validation.

Accessibility is the equivalent of building a new house, where we can add ramps or make doorways wider than normal to make it accessible for everyone. Basic accessibility isn't difficult or complex, but it must become a part of the development process; when left to its own devices, it will make it harder to move around the house, for those who need extra help to do so! In tandem with accessibility comes validation, which is very much like the Physics of cooking; if we work within the rules of validation, we can produce a masterpiece, while working outside of best practices is likely to lead to disaster.

It would be hard to produce a website without some form of decoration though; using HTML alone won't produce a very exciting effect! It's for this reason that we employ CSS to add final touches to our website, where we can tweak the positioning, add animation, or alter the colors of the elements on the page. Just as you can't build a house without cement, you can't produce a website without using CSS at some point in its creation.

Using CSS does not come without its limitations though—as it has evolved over the years, the support for its functionality has changed. One can argue that it has come a long way since its incarnation back in 1996, but at its very heart, it will always suffer from some core deficiencies. Let's take a look at these in more detail.


The limitations of using CSS

If you've spent time working with CSS, you will know the pain and heartache suffered when working with CSS—and all in the pursuit of creating that perfect site! Those who are still somewhat new to working with CSS will, at some point, fall foul of some of the limitations of CSS, which include:

  • CSS is heavily dependent on browser capability—it is impossible to display the same content in every browser in the same way. We can get around this, but not without the expense of having to add vendor-prefixed statements. This can lead to pages with a lot of repeated code, making them slow and difficult to maintain, where even the smallest change requires a lot of effort.

  • Not every browser supports every feature within CSS—this is particularly true of CSS3. This means we need to implement some form of graceful fallback for the affected browsers if we are to maintain some form of visitor experience.

  • The advent of CSS made a functionality such as columns on a magazine website much easier, although it is still not perfect. To achieve perfect columns, we will require JavaScript or jQuery to tweak the code, which makes the page less accessible (for example, making it harder for those using screen readers). It also has an effect on the use of progressive enhancement, where content should be enhanced using a functionality, such as CSS3 or jQuery, and not reliant on it.

  • It is impossible to target specific ranges of content, without altering the markup to include placeholders; should these placeholders change, then the associated CSS must also change.

  • We can't include a rule from one CSS style in another, nor can we name a rule—the latter of which could be used by client-side scripts, even if the selector that is being referenced changes.

By now, you're probably thinking that it is all doom and gloom when using CSS; fear not, we can fix this with the help of CSS preprocessors to help make our development more effective.


The benefits of using CSS preprocessors

If you've spent time working with CSS, one of the first questions you may ask yourself is "Why do I need to use a preprocessor?" It's a valid question and you certainly won't have been the first person to ask this either! Let me explain this in more detail.

CSS is known as a declarative language—this means that the rules we use to declare what happens to an element will be the rules that the browser uses to paint the results on the screen. If, for example, we want a block of text, such as a printed comment, to be in italics, then we will use something akin to the following code:

.comment {
  font-style: italic;
  font-size: 12px;

The browser will then render this on the screen in 12 px italicized text.

This example is very straightforward—it could be used anywhere. The trouble is, we may need to specify the same styling attributes elsewhere. We could use the .comment class, but what happens if we want to change the size? Or, perhaps render the text in bold instead?

Changing the style rules to suit one element could break them for the original element, which is not ideal. Instead, we will need to create multiple style rules that apply to specific elements, but which duplicate this code—this could make for very verbose CSS! Just imagine that we end up having to create a selector such as the following:

.article #comments ul > li > a.button {
...some style rules...

This isn't an easy selector to understand, let alone apply styling to, right? We can eliminate this issue of duplication using Less—it is possible to set one style block at the start of our Less style sheet and then reuse this style at every instance in our code, in the same way as you might use the autotext function to add predefined text to a document in Word, based on a key phrase. If we make a change, we only need to do it once—Less will automatically update our code, avoiding the need to do it manually. Imagine doing this for the dozens of buttons you might have on an e-commerce site and the benefits will soon be apparent!

This might come across as an alien concept in CSS—after all, I am sure we are used to writing code manually and spending many hours perfecting it. You might well have some misgivings about using a CSS preprocessor to take out some of the grunt work, particularly as it is satisfying when you manage to achieve that stunning piece of CSS artwork for a client. It's perfectly natural—let's take a moment to consider some of the common misgivings about using CSS preprocessors.

Why not just write normal CSS?

Many people will often ask, "If we're producing CSS, why aren't we just writing it instead?" It's a common reaction; after all, we use CSS every day to solve any layout problem thrown at us while building beautiful responsive sites that work in any browser. The last thing we want is to not look like we know what we're doing, right?

Let me be clear from the outset: the purpose of using Less is not to write better CSS. If you don't understand how to use CSS now, then Less won't help you fill that gap. What it will do is help you write CSS faster and more easily, while making your style sheets more manageable at the same time. Let's explore some of the reasons why we should switch to using a CSS preprocessor, such as Less, in more detail:

  • CSS preprocessors, such as Less, don't break browser compatibility—each CSS preprocessor produces valid CSS

  • CSS preprocessors help to make our CSS DRY (Don't Repeat Yourself)—we can create variables from reusable CSS properties, which helps us to make our code more scalable and manageable, as we can break it down into smaller files that automatically compile into one larger style sheet

  • CSS preprocessors, as we'll see throughout the book, contain some useful features that help remove some of the tedium that frequently appears when writing CSS styles, by automating some of the low-value tasks that have to be performed

  • We can take advantage of the nesting capabilities of CSS preprocessors, which leads to a more natural style of writing, where we can use a form of shorthand to produce the desired effect

Now that we've explored some of the advantages of using a CSS preprocessor, let's delve in and get acquainted with Less for the first time. We'll go on a whistle-stop tour in order to give you a flavor of what to expect in Less. Don't worry if you don't understand it just yet; we will cover everything in more detail throughout the book.


Introducing Less as a solution

First created in 2009 by Alexis Sellier, Less is a dynamic style sheet language originally written to use Ruby; this was soon deprecated in favor of the significant increase in speed gained by rebasing the library in JavaScript. It is designed to be used by both the client and the server—the latter with help from Node.js, which we will cover in Chapter 3, Getting Started with Less.

Less was built as a superset of CSS, which means that it contains more advanced tools than traditional CSS. This allows us to write less code while still compiling it to valid CSS. The key to this lies in how we can use Less to produce better organized, more readable code. To see this in practice, let's take a look at a quick example of what we mean.

Imagine that you've written the following sample of CSS code—it's a perfectly valid CSS, even though it won't actually produce any useable results:

header { 
  margin-bottom: 25px;

header nav { 
  height: 25px;

header nav a { 
  color: #151b54;

You might have noticed though that we've had to repeat ourselves a little, which is not ideal, but a necessary evil when writing such styles. The code is readable in our example, but if we had developed this to any degree, the repetitive nature of the selectors (such as header nav div.first div.thumb .img-wrapper img) could make it harder to follow the code.

One of the core concepts of Less is to use the DRY principle when writing code—we can take advantage of its nested metalanguage syntax to reduce the code by nesting our statements. If we take the previous block of code and reform it using Less, it will look as follows:

header { 
  margin-bottom: 25px; 
  nav {
    height: 25px;
    a { color: #151b54; }

Here we compile to the CSS we've just seen.

Notice how we managed to reduce the amount of code we had to write while making the code easier to read, by grouping styles and adopting a more natural flow. Nested metalanguages are hierarchy based, where we can group related declarations together and reorder them in some form of hierarchy that abstracts each level while including the higher level. Less will naturally group these related declarations together, which is a great benefit if a CSS style sheet is edited by multiple individuals.


If you would like to learn more about nested metalanguages, you may want to browse to http://en.wikipedia.org/wiki/Metalanguage#Nested_metalanguage. Note that it's a somewhat dry reference (pun intended!).

To prove that this does indeed compile to valid CSS, you can see the results of compiling the previous Less code in Crunch!. Crunch! is a CSS editor and compiler for Less, which we will cover in more detail in Chapter 2, Building a Less Development Toolkit. You can code in Crunch! as shown in the following screenshot:

Don't worry if nesting code doesn't mean a great now—we will cover nesting in more detail in Chapter 4, Working with Variables, Mixins, and Functions. This is just one of the many functions in Less that will help revolutionize your CSS development. Let's take this a step further by delving into some of the reasons why you should use Less, in more detail.


Why you should use Less

We've already seen that Less is designed to help make CSS easier to manage and maintain. Let's explore some of the key features in more detail, which will give you a taste of what to expect with Less and demonstrate how Less can make writing CSS easier.

Reducing redundancy with variables

How many times have you worked on a website where you needed to declare the value of a color in CSS, such as #ececec? 10 times? 20 times? It's rare that you will get the color in the first time; it is more likely that you will need to revise it, which can create a real burden when working in CSS. No matter how many times it ends up being, one thing is true: it is not easy to remember the hex value for each color.

Less can help by allowing us to define colors as variables, with more memorable names. A variable is merely a mechanism for referencing a value; take a look at the following three examples:

@red: #de1446; 
@blue: #4a14de; 
@green: #32de14;

The beauty of Less is that once we've defined these variables, Less will automatically update any instance where they are used if we decide to change the hex values at a later date.

Understanding the syntax of variables

In Less, the @ sign indicates that we are defining a variable; following this (@) symbol, we normally have the name of the variable (with no spaces), and the colon indicates the end of the variable name. This is followed by the value, with a semicolon used to close the statement. In this case, the @red variable refers to the red color we want as a hex value. Once we've defined these variables, we can use them anywhere in our Less style sheet shown as follows:

.red-box {
  color: @red;

When we compile it, the following valid CSS is produced:

.red-box {
  color: #de1446


In Less, compile just means to go from Less to CSS. We will use this term frequently throughout the book.

Writing and remembering variable names is far easier than remembering unnatural hex values, right? Moreover, when these values need to change, we only need to update them in one location and Less takes care of updating everything else. No more need to perform a "find and replace" when changing colors—this can be a huge timesaver!

Creating reusable blocks of code

So we've created some variables…but reusable blocks of code?

One of the benefits of using Less is that we can group together multiple lines of code and turn them into a reusable block that we can drop in our code. Let's take a look at an example:

.serif() {
  font-family: Georgia, 'Times New Roman', serif;

This is a very simple example of a reusable block of code, or mixin. If you've spent any time developing JavaScript or jQuery, then you may recognize a similar behavior in the form of classes; mixins work in pretty much the same way.

Mixins, by themselves, won't do anything and to make them useful, we need to call them from our code using a placeholder, as highlighted in the following code:

p {
  font-size: 10px;
  line-height: 1.25em;

This compiles to valid CSS:

p {
  font-size: 10px;
  line-height: 1.25em;
  font-family: Georgia, 'Times New Roman', serif;

See how, with just one short keyword, we've asked Less to drop in something more involved? One small point to note is the use of () against the mixin name—Less will compile the reusable code (or mixin) to valid CSS, but it will not render the compiled mixin on the screen. The great thing though is that we can simply call .serif; wherever we need to render text using the defined font-family attribute.

Generating values automatically

In more recent browsers, you are likely to find websites using RGBA (Red Green Blue Alpha) and HSLA (Hue Saturation Lightness Alpha) colors, rather than the typical hex values that we saw in the previous section.

Not every browser supports these color formats—to get around this, we can declare a hex value first, followed by its RGBA or HSL equivalents. As an example, we might write something similar to the following code in order to turn the text set with the h1 attribute to dark brown:

h1 {
  color: #963529;
  color: rgba(150, 53, 41, 0.5);

If we're choosing colors in a graphics package such as Photoshop or GIMP, we might occasionally struggle to get both the values and might need to resort to alternative means. Thankfully, this is not an issue with Less as it allows us to use functions to create new values automatically.

Why will we do this? The answer is simple: all we need to do is provide a color value using one format, such as RGBA. We can then use Less' functions to convert it to a different format—we can then avoid any confusion about ensuring we've provided the right values, as these will be worked out automatically by Less.

Let's take a look at a quick example of how this will work:

.brown-color {
  @rgbaColor: rgba(150, 53, 41, 0.5);

  color: fade(@rgbaColor, 100%);
  color: @rgbaColor;

Here, we've used a simple variable to define the base color before using the rgba color function to convert it to its RGBA equivalent value, with the alpha value set to 0.5. If we compile the Less code, it produces the following CSS:

.brown-color {
  color: #963529;
  color: rgba(150, 53, 41, 0.5);

The alpha channel in our example is set at 50 percent. This means that we can see 50 percent of whatever is behind the color in the browsers that understand RGBA. The use of functions will really come into their own when creating themes for sites—we could potentially create a whole host of colors from just two to three base colors!

We will explore more about the color functions later in this book, in Chapter 12, Color Processing with Less.

Forgetting about vendor prefixes

The beauty about using CSS3 is that there's no need to always use images, when we can often achieve the same result using pure styling alone. Trouble is, catering to all these new features, such as background gradients, animations, box shadows, and the like, means that we often have to use vendor prefixes or different syntaxes to ensure that the site can be viewed by the widest possible audience.

This can be a real pain but not so much with preprocessors. As you will see later in Chapter 4, Working with Variables, Mixins, and Functions, we can create a mixin or a small block of predefined code that can literally be mixed in our Less style sheet and can be used to create valid CSS. Take, for example, the following block of code, which is used to produce rounded corners:

.roundcorners { 
  -webkit-border-radius: 4px; 
  -moz-border-radius: 4px; 
  -ms-border-radius: 4px; 
  -o-border-radius: 4px; 
  border-radius: 4px; 

With Less, there are hundreds of mixins that are available online (more of which we will cover later in the book), which we can use in our code. Instead of having to remember what each style needs in terms of prefixes and syntax, we can just use the following code:

.roundedcorners {

The preceding code produces exactly the same CSS that was once compiled; Less automatically adds all the vendor prefixes, which is a great time saver.

Creating media queries and animation the simple way

The advent of mobile devices has created a need for responsive websites, which will display content only if the rules meet a specific environmental condition or breakpoint. A good example is determining the size of the screen in use when browsing a responsive website.

This normally means having to write a number of queries for each breakpoint in a design. As an example, we could write the following (simplified) CSS to change the typography for a particular device:

@media only screen and (max-width: 529px) {
  h1 {
    font-size: 0.7em;

@media only screen and (max-width: 949px) {
  h1 {
    font-size: 0.9em;

@media only screen and (max-width: 1128px) {
  h1 {
    font-size: 1.1em;

Even though this is only setting the size for the h1 attribute, it seems like a lot to remember. We can simplify the code using the power of Less:

@smallwidth: ~"only screen and (max-width: 529px)";
@mediumwidth: ~"only screen and (max-width: 949px)";
@largewidth: ~"only screen and (max-width: 1128px)";

h1 {
    @media @smallwidth { font-size: 0.7em; }
    @media @mediumwidth { font-size: 0.9em; }
    @media @largewidth { font-size: 1.1em; }

We start by declaring three variables, each containing the media query statements. These are static values and will only change if we decide to add or modify any of the supported breakpoints. It isn't essential to use them in this instance, but it will help make the nesting solution easier to read!

We then call each media query using @media, followed by the variable that contains the breakpoint we wish to test against. The key point here is that while it might look like @media is repeated, we can't base our nesting style on @media as the code will fail to compile. Instead, we need to base it on the h1 selector for the code to compile correctly.

Reusing code across multiple projects

One of the limitations of CSS is that we often find ourselves applying the same values across multiple elements, throughout each site that we build. On a small site, this is less of an inconvenience, but for larger sites, there is a greater risk that we may miss updating a value, which could produce unexpected results. We've seen how you can reduce (or even eliminate, with good planning), the risk using variables—what if we could reuse our code in future projects?

This is not as crazy as it might seem—we may develop a specific drop-shadow style for buttons that we like and want to reuse. The conventional way is to store this in a text file, database, or the likes, and then dig it out each time we need to reuse it. It's a cumbersome way to do it, even if it does work—the need to do this is eliminated if we use a preprocessor.

We can simply store the code in a file, in the form of mixins or reusable blocks of code. If we need to reuse any of them, we simply add the file to our project and use the following command to import the contents:

@import "mixinfile.less";

The beauty of using Less though means that it will only import those mixins that are needed for our project in the main CSS file.

Compressing CSS automatically for faster websites

So far, we've talked about some of the compelling features of Less—a fraction of what it offers—there is a lot more that we will cover throughout the book as well as taking a look at some of the more practical uses of Less.

There is one key thing to writing CSS that we've not mentioned: the ability to compress your style sheets as part of releasing your site into production. Compressing our style sheets removes white space and allows us to concatenate multiple files in one master CSS file.

Why should you do this? The answer is easy: it will make style sheets a fraction of the size of the original, which saves on bandwidth. While this is probably less of an issue for normal Internet connections, it is critical for those using mobile devices with limited bandwidth.

How will you compress your CSS? Sure, we could compress it using an online tool, but this means using an extra tool, which adds to your already busy development. There is no need to do this when using Less—if you compile your code using one of the GUI tools, such as WinLess, or even the command line, you can set it to compress the code at the same time.

This is just a taste of what Less can offer. Before getting up and running the development tools we will need for using Less, let's take a brief look at what CSS4 will offer and how this might affect preprocessor tools such as Less.


Supporting CSS4 standards within Less

With the advent of CSS2 and CSS3, it is natural to assume that CSS4 will arrive at some point in the future. You are probably wondering how it might affect CSS preprocessors—let's take a look at what CSS4 is likely to mean for Less.

Officially, there is no such thing as CSS4. Strange as it might seem, we won't see the appearance of a new global standard; CSS4 instead will be grouped under smaller headings, of which each will have its own level. There is still a long way to go, but one of the groupings that is closest to being finalized is CSS4 Selectors.


You can see more details about the proposed changes for CSS Selectors in the W3C's draft proposal at http://dev.w3.org/csswg/selectors4/. There is an interesting discussion on the possibilities of using Selectors at http://vandelaydesign.com/blog/design/some-interesting-possibilities-with-css4/.

Although these have been around since the beginning of CSS, CSS4 brings a number of new logical operators, such as :not and :matches, as well as some new local pseudo classes in the form of :any-link or :local-link. The latter, in particular, brings some useful features to styling links, as shown in the following code example:

   color: red;

   color: green;

   color: blue;

   color: yellow;

   color: gray;

We can rewrite this using the following code in Less:

nav {
  &:local-link(0) { color: red; }
  &:local-link(1) { color: green; }
  &:local-link(2) { color: blue; }
  &:local-link(3) { color: yellow; }
  &:local-link(4) { color: gray; }

If we compile this code, we can see the results within a page that has a breadcrumb trail—take, for example, the URL as http://internetlink.com/2014/08/21/some-title/, and this in the form of a breadcrumb trail as follows:

  • Home (http://internetlink.com/)

  • 2014 (http://internetlink.com/2014/)

  • August 2014 (http://internetlink.com/2014/08/)

  • 21 August 2014 (http://internetlink.com/2014/08/21/)

  • Article (http://internetlink.com/2014/08/21/some-title/)

The first link will be red, the second will be green, the third blue, then yellow, and finally gray.

Supporting future CSS standards within Less

Support for future CSS standards (or CSS4, as it is frequently termed) is still very much in its early stages within Less. Some progress has been made to allow the use of selectors in Less, which can be used with the ampersand symbol, as we saw earlier in the Supporting CSS4 standards within Less section in this chapter.

At the time of writing this book, the developers have refrained from adding too many new features for CSS4, as most of the current proposed changes are still in the draft state and are subject to change. The main feature added so far is that of support for attributes, which appeared in Version 1.4 of Less—others will appear once the specification has been finalized and support has appeared in more than one browser. The key thing to note though is that any CSS4 standard with CSS3 syntax is automatically supported in Less.

There will still be a need for Less once CSS4 standards become mainstream; Less will evolve to include the new standards while still allowing us to be more efficient when writing CSS.


How much support does my browser offer for CSS4?

As an aside, you may like to test your browser of choice to see how much support it offers for CSS4; browse to http://css4-selectors.com/browser-selector-test/ and then click on Start test! to see the results.



In this chapter, we started with a brief look at the role of HTML and CSS in designing websites, and covered a few of the limitations that CSS has when styling elements on web pages.

We then talked about how CSS preprocessors can help solve some of these issues; we covered the critical question that people will often ask, which is, why we should need to use them when we are perfectly au fait with writing valid CSS. We then introduced Less as one of the preprocessors available and as a possible solution to some of the issues we face with CSS.

We then rounded up the chapter with a look at some of the reasons why Less should become part of your development toolkit, as well as some of the features available for helping you to manage your CSS development. In the next chapter, we'll start to take a more in-depth look at the syntax of Less and how we can compile it to create valid CSS.

About the Author

  • Alex Libby

    Alex Libby has a background in IT support. He has been involved in supporting end users for almost 20 years in a variety of different environments; a recent change in role now sees Alex working as an MVT test developer for a global distributor based in the UK. Although Alex gets to play with different technologies in his day job, his first true love has always been with the open source movement, and in particular experimenting with CSS/CSS3, jQuery, and HTML5. To date, Alex has written 11 books on subjects such as jQuery, HTML5 Video, SASS, and CSS for Packt, and has reviewed several more. Responsive Web Design with HTML5 and CSS3 Essentials is Alex's twelfth book for Packt, and second completed as a collaboration project.

    Browse publications by this author
Learning Less.js
Unlock this book and the full library FREE for 7 days
Start now