Bibliographic Information

Instant LESS CSS Preprocessor How-to

By: Alex Libby;
Publisher: Packt Publishing
Pub. Date: February 22, 2013
Print ISBN-13: 978-1-78216-376-3

Autorefreshing styles using watchr (Must know)

In this exercise we're going to take a look at a simple, but useful feature called watchr. This allows us to make changes to any less file while still in development, and for us to reload the page without having to force a complete reload of the page from the server.

Note

Note that this exercise will be in two parts; the first part will be to make the changes to your LESS/HTML code, and the second part will be to preview the changes in your browser.

Getting ready

For this exercise you will need to avail yourself of a copy of your code from the Installing LESS section, as well as a normal text editor of your choice.
For the second part of this exercise, if you want to use a local web server to preview your result, you will need to download and install an appropriate web server such as WAMPServer for Windows, available at http://www.wampserver.com/en. There will be similar products available for Mac (such as MAMPServer) and Linux users. It is best to try several, and remain with whichever you find easiest to use. For the purpose of this task, I will assume that you have downloaded and installed WAMPServer. If your settings are different, then please alter them accordingly.

How to do it...

  1. Let's begin by opening up a copy of the code from the Installing LESS section. Immediately below the call to the LESS library, insert the following:
  2. To test it, you need to fire up your local web server, and then save a copy of the HTML and LESS files from the first task into the server's www folder; for WAMPServer, this is normally c:\wamp\www.
  3. To preview the changes let's browse to your HTML file from within the server. You need to enter the appropriate URL into your browser, which will be something like this:
    If all is well, you should not see any changes yet.
  4. The change comes when changing the LESS code. Go ahead and change the hex code for the @color-button value, as follows:
  5. Now go to your browser and alter the URL, so it looks something like this: http://127.0.0.1/less/Chapter%201/test%20Less%20include.html#!watch
  6. Press Enter to reload the page. You should see the color change from the original red to a dark green as shown in the following screenshot:

How it works...

When working with LESS, you will find that compiled styles are stored in the localStorage area of the browser, and that they remain there until the localStorage area is cleared. This means you will have to force a refresh from the server in order to view any changes.
To get around this, you can force the browser into a development mode, which prevents the browser from caching the generated CSS files. The addition of !#watch at the end of the URL then acts as a trigger; it forces the browser to update the generated CSS style, without you having to force a refresh from the server.

Note

Note that in some instances, you may find this doesn't work when using Google Chrome; Chrome doesn't load local files from the PC's filesystem by default, due to a known issue with loading JavaScript files.
It's time for us to now get stuck into writing some LESS code. Over the next few recipes, we're going to turn our focus to looking at the constituent elements of the Less library, beginning with using Less variables.

Using mixins in LESS (Must know)

So far we've looked at creating variables in Less. It is time to take things up a notch, and take a look at a key part of Less functionality: mixins.
What are mixins? Put simply, mixins are preset blocks of CSS that you can literally mix-in (pun intended!) to produce new CSS styles. They are very much like the building blocks needed to build a house. On their own, they may not be very useful, but once combined into another style, they can become very useful. 

Parametric mixins without parameters

When you start using mixins, you will find that there will be instances when you want to use a mixin to help reduce the code in your LESS file, but which doesn't need to act directly on any element or selector within your website. It would be great, therefore, if you could set it so that LESS didn't show it as part of the compiled output. This is very easy to do; let's take a look at how to do it.
Imagine you have two styles, where .alert is the mixin, and .error_message is the style using that mixin:
.alert { background: red; color: white; padding: 5px 12px; }
.error_message { .alert; margin: 0 0 12px 0; }
Normally, when compiled, it would show the following CSS styles, which are perfectly valid, but the CSS would include the mixin style, which we don't necessarily need to include:
.alert { background: red; color: white; padding:5px 12px; }
.error_message { background: red; color: white; padding:5px 12px; margin: 0 0 12px 0; }
We now add () after the initial style name as follows:
.alert() {
background: red;
color: white;
padding:5px 12px;
}
.error_message { .alert; margin: 0 0 12px 0; }
We will get the following CSS:
.error_message { background: red; color: white; padding:5px 12px; margin: 0 0 12px 0; }
Using this method means that you can build up a number of mixins throughout your LESS file, and set LESS to incorporate those styles where appropriate, without including the original mixin styles.

Pattern-matching in LESS (Must know)

In the previous section we focused on how you can use variables to help build up reusable blocks of code, or mixins, but what if you could control which styles are used and when? Huh? You're probably thinking that CSS can do this already, at least in the part where you can define which styles are used. After all, this is standard functionality, right?
Sure it's standard, but not the ability to determine that if say color A is used, then color B should be used, and not color C. This is where you can use Less to create guarded mixins. In this exercise we're going to show a number of squares on screen, where the background color is being determined dynamically, based on how light or dark the color has been set on one of squares.

Getting ready

For this exercise all we need is our text editor, and a copy of the template file we created at the start of this chapter.

How to do it…

  1. Open up your normal text editor, and save a copy of the template file we created earlier at the start of the chapter as test less guarded mixins.html. Add the following highlighted lines:
  2. Create a new document in your text editor, and save it as test less guarded mixins.css and then add the following line to your HTML code:
  3. In your LESS file, add the following styles. We'll break it down into a number of sections, starting with the setting of basic values, and the control statement to determine which background color we're going to use:
  4. We need to add the styles that will determine how the background will be styled, and which control the DIV box sizes:
  5. Let's now add in the individual styles for each of the three squares shown on screen:
  6. The observant among you will have noticed the call for .box-shadow, but that we've not set the style for this; let's go ahead and fix that by adding the following lines:
  7. If all is well, you will see the following when previewing the result in your browser:
    How to do it…

How it works...

The key behind guarded mixins is that they only take effect if a particular condition is true. A good example is controlling the color used on the background of a page. If you have elements on page that use a light color, you would most likely want a dark color, and certainly not white! Equally, the converse is true; if your elements are dark in color, you may well want a light (or even white) color background.
Let's take a look at an example:
.set-bg-color (@text-color) when (lightness(@text-color) >= 50%) { background-color: #fff; }
.set-bg-color (@text-color) when (lightness(@text-color) < 50%) { background-color: #ccc; }
Here we've set the .set-bg-color property to be either gray or white, depending on whether the @text-color variable is either a light (that is, lower than 50 percent), or a dark (greater than 50 percent) color. When compiled, you will get the correct background, based on whatever value has been set for @text-color:
.box-1 { color: #BADA55; .set-bg-color(#BADA55); }

There's more…

Although this recipe was designed to be overly simple, you can do some fancy things with it, such as recursion, where LESS can call itself with an updated value creating a loop. You're probably thinking: where can I use that? Easy! Did you ever have to build a number of identical icons, which all use similar CSS? How about building them into a sprite, then using LESS to generate the CSS for you, using a loop? The styles will all have the same text prefix, such as .myclass1, .myclass2, and so on, but it's a small price to pay if it can save you a heap of work, as long as you use a sensible prefix!

Note

If you want to see the example code on how to do this, take a look at the following post:

Using JavaScript evaluation in LESS (Should know)

A powerful feature within Less is the ability to use basic JavaScript to generate CSS, such as using the screen.height function to determine how big your visitor's screen is. In this exercise we're going to demonstrate the power of using JavaScript within Less to draw a simple shape on screen, which uses the screen.height function of JavaScript.

Getting ready

For this exercise all we need is your text editor.

How to do it…

  1. We'll begin with opening a copy of the template we created at the start of this chapter; add the following lines, and save it as test Less javascript evaluation.html:
  2. Create a new file, add the following lines of code, and save this as test Less javascript evaluation.less:
  3. Test the HTML file in your browser; you should see something like the following screenshot:

How it works…

Although this is an overly simplified example, it serves to illustrate how you can use JavaScript to determine how big the box should appear. The use of LESS code is based around standard JavaScript code, but must use the ~`…` format to ensure that it is correctly interpreted by the compiler:
#testbox {
background-color: orange;
height: 100px;
width: 640px;
}

Tip

Note that using JavaScript in CSS can produce some very powerful effects; you should take care over using it, as it is open to abuse, and can be a security risk on your site if you are not careful!

Creating colors with operators in LESS (Should know)

At the start of the book, we took a look at how you can use variables to assign values in your CSS styling; the observant among you may have spotted something: we were using some basic operators to create colors. In this recipe we're going to extend this principle and use it to style one of the most important components of any website—the humble button! Normally, you would specify styles either using a selector ID or a class. While it will work, it will make things harder when updating or changing styles. Less can really help here; in this exercise we're going to create a base button, using the color function. We'll also look at how to alter the fill-in and border colors used at the same time, by altering the base color.

Getting ready

For this exercise all we need is our text editor.

How to do it…

  1. Let's start by opening a copy of the template you created at the start of this chapter, adding the following lines, and saving it as test less operators.html:
  2. Open your text editor, create a new document, and add the following lines; save it as coloroperators.css:
  3. If you preview the file in your browser, you will see the following:

How it works…

In this exercise we've used a simple operator to add or subtract a given number from the HEX code to arrive at the border color. In this instance the border color is #B02222, which gives the button a slightly darker color than that of the main button.

There's more…

The beauty of using variables here is that if you suddenly decide you want to change the color scheme on your site, you only need to change it in one place; all of the borders will be updated at the same time to a suitable shade that fits in with the new color. We can take this a step further and mix in some gradients in the LESS file. This works best if you choose a mid-point color and use this to define your gradient. A good example is to make the start of the gradient lighter and finish on a slightly darker color:
body { padding: 20px; }
@color-button: #faa51a;
input.submit {
@color: #faa51a;
background: -webkit-gradient(linear, left top, left bottom, from(@color + #151515), to(@color - #151515));
background: -moz-linear-gradient(top, @color + #151515, @color - #151515);
border:1px solid @color-button - #222;
padding:5px 12px;
}
This results in a button with a nice looking transition effect as shown in the following screenshot:

Creating colors with functions (Should know)

In this recipe we're going to use the power of LESS to create colored
tags, where the colors are chosen dynamically using the chosen base color and a number of functions of LESS.

Getting ready

For this exercise all we need is our text editor.

How to do it…

  1. Open a copy of the template that we created at the start of this chapter in your usual text editor, add the following lines, and save it as test less colors.html:
  2. Create a new document, add the following lines, and save this as colors.less:
  3. Open the file in your browser. If all is well, you will see the following appear:
  4. We're going to use a different function here, so we need to alter the descriptions shown against each
    tag first, otherwise they won't make sense:
  5. In this example, we're going to use two new commands—desaturate and saturate—so alter the CSS as follows:
  6. Preview the results in your browser; you will now see a completely different set of colors being used:
  7. We're going to use the Spin keyword now, so we need to alter the descriptions so they make sense:
  8. We need to update the styles as shown in the following highlighted lines of code:
  9. If all is well, you should see the same as the following screenshot if you preview the file in your browser:

How it works…

Although we've worked with using hex codes for colors throughout the previous two exercises, it is important to note that every color used in LESS is actually converted to an HSL (hue, saturation, lightness) equivalent.
What's the reason for this, I hear you ask? It's simple! Unless you have a hidden talent in being able to speak in HEX, most people find that HEX values don't come naturally to them. While some HEX colors such as #ff0000 are relatively easy to decipher, you'd be hard pressed to know that something such as #1f6b2d would translate as deep green!
The beauty of using HSL means that if you have an existing color, such as #e147d4 (magenta-purple), and wanted a creamier version, then you can easily do this:
@color: #e147d4;
@new_color: hsl(hue(@color), 35%, 77%);
The new color will maintain the same hue as the existing one, but have a different saturation and brightness; it would be harder to work out the the resulting #c480bf code if you are thinking purely in HEX.

There's more…

You can also use functions within functions when working in LESS. For example, if you wanted to desaturate and spin a color, you can do so by executing the following code:
@color: #c480bd;
.class { background-color: desaturate(spin(@color, 18), 12%); }
This is great, but it does highlight one small thing though: the similarities in each LESS style. This exercise was deliberately simplified, but if you were to use similar principles to style a number of similar, but more complex items, you could end up with a lot of duplicated code, right? This isn't an issue if you are using LESS; you can group a number of styles together using namespaces, which I will show you how to use in the next recipe.

Grouping/nesting styles in LESS (Should know)

If you regularly develop code, you may well have used namespaces in some form or other. Did you know you could use them in CSS?
That's right! With the power of LESS comes the ability to group CSS styles into logical groups, or namespaces, which you can reuse throughout your code. In the event you need to alter styles on some of the items you are styling, you can do this by adding additional styles that only apply to certain items. Let's take a look and see how this works, using a simple example of styling three buttons from a basic form; this is adapted from a tutorial created by Nick La, at http://webdesignerwall.com/tutorials/css3-gradient-buttons.

Getting ready

For this exercise all we need is a text editor. Everything else will be provided within the code.

How to do it…

  1. Fire up your normal text editor, save a copy of the template we created at the start of this chapter, and add the following in thesection:
  2. Add the following code and save it as test less namespaces.html:
  3. Create a new document and save it as namespaces.less; there are a lot of LESS styles to add, so let's begin with the base button style:
  4. The next block controls the individual color styling; we begin with creating the base colors and styles:
  5. We need to add some action to show when we hover over buttons, so go ahead and add the following lines of code:
  6. We finish creating the styles by adding in the :active pseudo class:
  7. Let's now tie them all together and set up the namespaces that we will use to style the individual buttons:
  8. If all is well, you will see the same as the following screenshot when viewing your work in a browser:

How it works…

In this exercise we've used the power of LESS to group blocks of CSS styles together, thereby reducing the amount of code we need to write; this is very much akin to what most programming languages allow us to do. In this example we've created a base style, which we called #button_base. Within this, we've set up two styles: one that controls the button appearance (.button) and the other that controls the text appearance (.medium). These styles can then be called from the three individual button styles that we are using to create the red, orange, and blue buttons.
This means that if you want to add more styles, you can easily do so; you could for example do something like this:
input.greybutton {
#button_base > .button;
#button_base > .medium;
.defined_color(#778899);
}
You can then add in an additional button in your HTML code using this style, it will produce the same as the following screenshot:

There's more…

While researching for this book, I had originally planned to use a format of code similar to this, to create each of the three buttons as follows:
input.redbutton {
#button_base > .button;
#button_base > .medium;
.defined_color(#fae7e9, #b73948, #da5867, #f16c7c, #bf404f, #bf404f, #ba4b58, #cf5d6a, #a53845);
}
The code worked okay, and served the purpose, but it wasn't the best way to create the buttons. I had to work out which colors to use, and pass through nine individual colors in all to the mixin... surely... I could do better!
I used the darken facility within LESS to work out the colors that should be used, as shown in the following code extract:
color: lighten(@color1, 10%);
border: solid 1px darken(@color1, 27%);
background: darken(@color1, 13%);
background: -webkit-gradient(linear, left top, left bottom, from(darken(@color1, 4%)), to(darken(@color1, 24%)));
This means I only need to pass through one color:
input.greybutton {
#button_base > .button;
#button_base > .medium;
.defined_color(#778899);
}
This surely has to be a better way to code a mixin! You just need to choose a single color to pass through (such as any from http://html-color-codes.info/color-names/), and LESS will work out the rest based on your chosen color.

Creating Polaroid effects using LESS (Become an expert)

The well-known Canadian web designer, Nick La, popularized a method of producing a Polaroid effect on some images using CSS3 and some pseudo selectors. You can see his demonstration at http://webdesignerwall.com/demo/decorative-gallery-2/. In this recipe we're going to adapt a copy of it to use LESS to achieve the same effect.

Getting ready

For this exercise, you will need to avail yourself of copies of a number of files mentioned as follows:
  • Some of the images from the demo, or copies of your own; for the purpose of this demo, I will assume you have used three images; if you have used different images, please adjust the code accordingly
  • The background and overlay images from the demo on the Web Designer Wall site
  • The mixin library files from lesselements.com and lessprefixer.com
And yes, you will of course need your text editor!

How to do it…

  1. Crank up the normal text editor of your choice, add the following lines of code, and save it as test less transform.html:
  2. Add the following lines of code inside thesection:
  3. Let's now add in the LESS code required to style our demo. Create a new document and save it as transform.less and add the following code, beginning with the background styles:
  4. Immediately after it, add the following gallery styles:
  5. We need to add the styles required to position the tape image:
  6. We can then finish by adding in the all-important CSS3 transform effect, which shells out to a transform mixin:
  7. If all has goes well, you will see the following in your browser when previewing your results:

How it works…

This recipe illustrates how you can adapt existing code to take advantage of the power of LESS to compile your CSS code. Although we've kept the code close to the original, we've been able to incorporate some useful LESS features:
  • In the second step we've used string interpolation to create a base folder for our images, so that changing this will update all instances automatically. We're also importing the prefixer and lesselements mixin libraries, ready for use in the code.
  • In the third and fourth steps we've incorporated nested rules to avoid duplication of style names.
  • Also in the fourth step we're making a call to the box-shadow mixin that we imported earlier in the recipe. We're also using string interpolation to pull in the overlay and tape images.
  • In the fifth step we're making two calls: one to the transform mixin in the elements.less library and another to the prefixer.less library for the box-shadow mixin. We're also using the same string interpolation technique you've already seen earlier in this book, which features in the second step of this exercise. This time it is to bring in the cork background image.

There's more…

The original LESS code was written to use a transform mixin available at http://css-tricks.com/snippets/css/useful-css3-less-mixins/, before finding one that had already been included as part of a library of mixins, which is available at http://www.lessprefixer.com.
In this instance either will work perfectly fine, although you may start with one you write manually. Don't be afraid to keep an eye out for existing mixins online; you may find a better option that helps reduce the number of imported files you use!
On the subject of imported files, there is one question we need to answer, which is: Does LESS behave if used with other libraries on the same site or page? Let's take a look at this as part of our next recipe.

Using LESS with other libraries (Become an expert)

As part of using new functionality, web designers or developers will always want to know how well it works with existing functionality. After all, there is no point trying to sell the need to spend lots of money on licensing a package that does everything you need if it doesn't behave well with other software!
In this exercise we're going to take a look at how you could use LESS in conjunction with other packages, using the Modernizr library as our example.

Getting ready

For this exercise all you will need is your trusty text editor, a photo (preferably in PNG format), and a copy of the elements.less mixin you downloaded earlier in this chapter. It doesn't matter what the subject of the photo is, I will assume for the purpose of this recipe that it is called photo.png and is 200 px by 300 px in size. I've used the spiral staircase image available from http://pixabay.com/en/spiral-staircase-stairs-58328/, and have resized it accordingly.

How to do it…

  1. Crack open the text editor of your choice, add the following lines of code to a new document, and save it as test less compatibility.html:
  2. Create a new blank document, add the following lines of code, and save it as compatibility.less. Make sure you have your copy of elements.less in the same folder as your exercise files:
  3. We need to add some more styles, create a new document, add the following lines of code, and save it as styles.css:
  4. If you preview the results in your browser, you will see something like the following screenshot:

How it works…

In this recipe I've used a demo created by Faruk Ates, which shows how to incorporate Modernizr into your site (if you want to see the original, it's available at http://www.alistapart.com/d/taking-advantage-of-html5-and-css3-with-modernizr/sample-medium.html), and I've reworked it to use LESS to build the CSS dynamically.
If you've not used Modernizr before, then key to Modernizr is its ability to work out if it supports a particular feature, and not the version of the browser being used. The latter is open to being unreliable. It inserts CSS styles which are then used to indicate if a feature is supported; it adds a no- tag to each style if it is not supported in your browser.
In our recipe I've converted a number of styles into LESS equivalents and hived them off to a separate file in our code; keeping them in the same stylesheet as the other CSS styles would have confused Modernizr and LESS. If you look closely at the compiled code in something like Firebug, you will see there are some styles there for features that are not supported, such as no-cssreflections. For those styles that are required, but are not supported, fallback styles have been included in the CSS and/or LESS files. If you want to see the difference, try viewing the same page within Firefox and IE and you will see a real difference!

There's more…

The beauty of LESS is that it creates standard CSS styles when compiled. This means that it could be used in a variety of environments; if it doesn't work, or the site is too big, when used dynamically, you can always precompile the code using something like Crunch and add the resulting CSS files manually. There is an array of other libraries which could be used with LESS. To whet your appetite, here are a few:
  • Yepnope.js (http://www.yepnopejs.com): This is often used with Modernizr; it's a basic way to determine support for a feature in your browser and decide whether to use the normal support or a fallback version.
  • Prefixr.com (http://www.prefixr.com): Although there are mixins available to support most of what is offered by this site (such as http://css-tricks.com/snippets/css/useful-css3-less-mixins/), you could still use it to ensure mixins are kept up-to-date with changing styles.
  • 320 and Up: This is billed as the tiny screen first responsive boilerplate; this uses LESS mixins to help reduce the style code required within the system. It's available at http://stuffandnonsense.co.uk/projects/320andup/.
  • Bootstrap: This is available at https://github.com/twitter/bootstrap; it's a frontend toolkit which contains a number of user interface components and interactions. It uses LESS extensively, principally in the form of mixins that are available for use in the library.
  • Respond.js: This polyfill library is available to download from https://github.com/scottjehl/Respond/, and provides CSS3-based media enquiry support for browsers that don't support them by default as part of building responsive sites. You may have to compile your LESS code first before including the Respond.js library.
  • Fraction.less: This is a boilerplate system available at http://fractionless.info/; it was based on HTML5 Boilerplate but adds support for LESS while removing some of the bloat from the original version.
  • Node.js: We've already touched on this earlier in this chapter briefly; Node.js (available from http://www.nodejs.org), is perfect as part of adding support for LESS and other libraries to text editors such as Sublime Text 2 (http://www.sublimetext.com) or Notepad++ (http://www.notepad-plus-plus.org/).
There are plenty more available online—happy hunting! In the meantime, let's turn our focus to using prebuilt mixin libraries and see how you can use these within your code as part of the next recipe.

Using pre-built mixin libraries (Become an expert)

Throughout this book we've looked at how you can write code more efficiently by using the LESS library. In particular, we've covered how you can create your own mixins, which will help save you time when writing code, particularly if it involves adding vendor prefixes! You could spend time writing these mixins, and this will surely be a valuable exercise, but it will take time that could be better spent elsewhere. Instead, why not have a look online to see if a mixin has already been written. Lots of people have written their own mixin libraries over time, and this could save you a lot of unnecessary work.
In this final recipe we're going to look at how you can use one such mixin library to create some progress bars. The code we will use is based on some I found posted at CSS Deck (http://www.cssdeck.com), which we will adapt to use with the mixin library at http://www.lesselements.com.

Getting ready

For this exercise you will need to avail yourself of a copy of the mixin from http://www.lesselements.com; the download file is available at https://github.com/dmitryf/elements/zipball/master. Other than this, all you will need is your normal text editor.

How to do it…

  1. Crank up your normal text editor, create a new document and add the following code, and save it as test less progressbar.html:
  2. Create a second new document, add the following LESS code, and save it as progressbar.less. There is a fair bit of code, so we will go through it section by section, beginning with the imports:
  3. We add the base LESS style for the progress bar. This uses two mixins: one of which is from lesselements.com, and the other is my own:
  4. Although the basic progress bar style is now defined, it's not going to look very stylish just yet, so let's fix that by adding in some more styles:
  5. The last part of the LESS styling is to give each progress bar its own colors. In this instance we're using red, green, and blue; the code shells outputs to one of my own mixins:
  6. The last step is to add the code for two mixins that are being referenced: one using the linear-gradient style and the other for repeating-linear-gradient:
  7. If all is well, you will see the following in your browser when viewing the results:

How it works…

Although the code in the LESS stylesheet may look complicated, in reality it is simpler than it looks; mixins work in a similar fashion as that of functions in most programming languages.
In this instance we've provided calls to four mixins in all; two are being referenced from the prebuilt mixin library from lesselements.com, and two reference my own LESS mixin file. In all cases we pass through a number of different variables, which LESS then substitutes in to the placeholders within each mixin. A key point not to forget is that although we've included more mixins than have actually been used, LESS will only include those that have been referenced from our style code, which in this instance will be .box-shadow and .border-radius, in addition to the other two that are being used.

There's more…

It is well worth doing research online to see if others have created any mixins that fit in with your requirements; there are hundreds of people who have created or contributed to mixins, either as individual ones or as part of a library.
To get you started, here are some you may want to look at for using within your projects:
There are plenty more available for you to try; you can pick whichever you prefer to use that fits your requirements, or perhaps create your own library!

These are notes I made after reading this book. See more book notes

Just to let you know, this page was last updated Monday, Dec 02 24