Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

CSS Pre-Processors: Exploring Less Processor

This article introduces you to the CSS pre-processor LESS. Since the installation and configuration until many ways of use.

This article introduces you to the CSS pre-processor LESS. Here I would be covering the following topics with relevant and simple examples (source code of the examples is attached at the end of the article for your reference):

  • CSS Preprocessors
  • Introduction to LESS
  • Terminologies
    • Variables
    • Mixins
    • Nesting
    • Operations
    • Functions
  • Comparison LESS with SASS

CSS Preprocessors

CSS is a simple language which allows to style properties of HTML elements using selectors. The styles are added in external style sheets and are stored in CSS files. When size of your project increases, you end up with much of repeating CSS code. This is a time to use CSS preprocessors.

What are CSS Preprocessors?

CSS Preprocessors are popular way of simplifying and writing more manageable CSS which adds extra functionality to the Cascading Style Sheet by using mixins, variables, operations and functions with which we can manage the CSS files to run faster. CSS as a language which has own feature set which are not enough to reusable chunk of rules such as unavailability of variables which leads to ambiguous data across the style sheet. To overcome this, the concept of preprocessor came into picture.

Following are some of the available preprocessors:

  • LESS
  • SASS
  • Stylus
  • Compass
  • Turbine
  • LiveReload
  • Prepros

In this tutorial, we are going to explain one of the most popular CSS Processors: LESS

Introduction to LESS

What is LESS?

LESS is a relatively new preprocessor which is dynamic style sheet language which enriches CSS with many features available in modern dynamic programming languages. It is often referred to as “dynamic css”. LESS is cross browser friendly that allows developers to reuse CSS elements and write LESS code with the same semantics.

LESS is designed by Alexis Sellier in the year 2009. It is often compared to SASS, which allows features such as variables, mixins, functions and other techniques make CSS more maintainable, themable and extendable. LESS is an open source preprocessor which has its roots in the Ruby programming language. Later on use of Ruby has been deprecated and replaced by JavaScript.

Features of LESS Preprocessor

  • LESS is super set of CSS and is based on JavaScript.
  • It is an intuitive and agile tool which solves the problem of code repetition and reusable code.
  • Once style is defined, it allows re-using wherever needed.
  • It saves time and reduces mistakes.
  • It is dynamic CSS, so it can be easily customizable.
  • Once variables have been defined, you can use them often.

What LESS can do

  • Provides variables in the CSS.
  • Using mixins feature., LESS allows reusing rule sets.
  • It allows nesting of styles in the structure.
  • It can do mathematical operations such as floor (), round () and color operations such as fadein (), fadeout () etc.

Compiling LESS

By using LESS, you could run the program very easily by adding the following lines of code in the tag of the HTML document.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

You can download the library from the official site of lesscss.org. The link is provided in the section of links at the end of the article.

One important thing to note here is to include the style sheet before the script as shown above.

Example

Let’s see one simple example of LESS preprocessor which takes .less file to apply styles in the document (Listing 1).

Listing 1. index.html

 <!doctype html>
<head>
<link rel="stylesheet/less" href="styles.less" type="text/css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/less.js/2.0.0/less.min.js"></script>
</head>
<body>
    <div class="shape" id="shape1"></div>
    <div class="shape" id="shape2"></div>
    <div class="shape" id="shape3"></div>
</body>
</html>

The code contains .less style sheets which can be linked to stylesheet/less by using rel attribute and you should include your style sheets before the script. You can also get less.js code by adding CDN within the tag as shown in the above example.

Now, let’s create one styles.less file with extension .less and add some CSS styles as per the requirement and link it to the page with code as shown in the above script.

styles.less

@primarycolor: #ccc;
.shape{
    display:inline-block;
    width:100px;
    height:100px;
    background:@primarycolor;
    margin:20px;
}

The code contains a class called shape which has css styles in the less file styles.less. It contains a variable called @primarycolor which gives background color for the displayed output by using value assigned to that variable.

We are running the program at the server side i.e. executing the program locally in the system. When we run the above script, we get the following output:

Output of index.html

Figure 1. Output of index.html.

Whenever we make a change in the styles.less file, the compiler will automatically generate the regular CSS format which the browser can read in the directory. In the below picture, you could see the changed css style:

CSS of index.html

Figure 2. CSS of index.html.

Terminologies

Variables

Variable in LESS do what exactly they do in other programming languages. LESS allows variables to be defined which can be declared with @ symbol and variable assignment is done with colon (:) which is similar to CSS. It can be a combination of letters, numbers, dashes and underscores. It is extremely easy to set global styles that can be changed in a single location rather than sorting through the code to find every instance of that file. You can store a value for a variable and then use the variable instead of using the value itself whenever there is a need in the program. You can refer to the name of the variable anywhere in the .less file.

For example:

@red: #CF142B;
@baseLineHeight: 22px;

Let’s take a simple format of variables and see how they will render once they are compiled:

@color: #CCCCCC;
.shape{
       background:@color;
}
h2{
      color: @color;
}

In the above example, we defined color variable and assigned the value #CCCCCC. We can use this variable whenever we want to use the gray color. When we compile the above code with LESS, we would get the following css code:

shape{
    background: #CCCCCC;
}
h2{
     color: #CCCCCC;
}

You can also display the variables with variable name as shown below:

@color: red;
@bgColor: ‘color’;
background-color: @@bgColor; //display background color with red;

Variables allow using of a name instead of a value which makes a style sheet much more understandable. If you want to change the value you need to go to one location in the style sheet to do so, which affects all the instances in the style sheet where you used this variable name.

Variable Scope

The place where the variable is available is called the variable scope. Define the variable at the start of the LESS file, which will be available to any code you write after it.

Consider one simple format of css style:

.class1{
     background-color: @grey;
}
.class2{
     background-color: @lightblue;
}

In this file, we have defined variables inside the CSS rule. The LESS file will not be converted since there is an error, because there is no variable outside of the rule set. So define the variable outside of an element as shown below:

@grey: #CCCCCC;
@lightblue:  HYPERLINK "http://www.colorcombos.com/colors/CCFFFF" \h #CCFFFF;

.class1{
     background-color: @grey;
}
.class2{
     background-color: @lightblue;
}

Example

Consider the following example which shows usage of variables. Create one html file called as shown below:

Listing 2. variables.html

<!doctype html>
<head>
<title>Variables Example</title>
<link rel="stylesheet/less" href="style_variable.less" type="text/css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/less.js/2.0.0/less.min.js"></script>
</head>
<body>
<h2>Example of Variables Section</h2>
   	 <div class="class1" id="shape1"></div>
   	 <div class="class2" id="shape2"></div>
  <div class="class3" id="shape3"></div>
</body>
</html>

Create .less file as shown below:

style_variables.less

@first_color:  #46A546;
@second_color: #0064CD;
@third_color:  #F89406;
@tag_color: #9D261D;

h2{
color:@tag_color;
}
.class1{
    display:inline-block;
    width:100px;
    height:100px;
    background:@first_color;
    margin:20px;
}
.class2{
    display:inline-block;
    width:100px;
    height:100px;
    background:@second_color;
    margin:20px;
}
.class3{
    display:inline-block;
    width:100px;
    height:100px;
    background:@third_color;
    margin:20px;
}

In the html file, we have defined three classes class1, class2 and class3 which contain css styles for their respective output in the style_variable.less file. We have declared three variables first_color, second_color and third_color with the specified values. One more variable called @tag_color to display the text color defined within the h2 tag.

When we run the above script, we get the following output:

Output of variables.html

Figure 3. Output of variables.html.

When we execute the program, the compiler will automatically generate the regular CSS format which the browser can read in the directory. In the below picture, you could see the changed css style:

CSS of variables.html

Figure 4. CSS of variables.html.

Variables can be used to store CSS properties such as width, height, font size, font family and other values that can be reused throughout the style sheet. It provides a constant value which can be reused in the entire style sheet. The main advantage of variables is, if you want to change the color, you need to change only the value in the variable.

Mixins

It is the other important feature of LESS, which provides functionality to mix the values of properties of one class in to another class without any special syntax by including the class name as its properties and behaves as a constant or variable. In other words, with mixins we can use entire properties from one rule set to another. The mixins are used to store multiple values and then that class can be used again and again.

How to use mixins in less?

Create one simple class as we do in regular CSS and store some different styles in that class. This class can be reused whenever in the code to achieve required functionality.

Consider following class with some CSS styles:

.font_styles {
     font-size: 15px;
     font-weight: normal;
     font-style: normal;
}

The mixin is now ready to be used and can be used wherever you need. If you want to provide mentioned styles to p selector, use the mixin shown below:

p {
     .font-styles;
}
Example Listing 3.mixins.html
<!doctype html>
<head>
<title>Variables Example</title>
<link rel="stylesheet/less" href="mixin_style.less" type="text/css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/less.js/2.0.0/less.min.js"></script>
</head>
<body>
	<p class="MyStyle">This is Example of Mixins</p>
</body>
</html>

Create .less file as shown below:

mixin_style.less

.MyMixin {
	font-size: 25px;
	font-style: normal;
	border: 1px solid #0f3c1c;
	border-radius: 10px;
	background:#F89406;
}
.MyStyle {
	.MyMixin;
}

The above example shows usage of mixins in less. We are using

tag with class “MyStyle” which has CSS styles in the “mixin_style.less”file. In this file, .MyMixin class contains CSS styles for the

tag. We are using concept of mixins to embed all properties of this class into another class called “.MyStyle” by including that class name as one of its properties.

When we run the program, we could see the output is the mixin itself and the CSS rule set as shown in the picture below:

Output of mixins.html

Figure 5. Output of mixins.html.

When we execute the program, the compiler will automatically generate the regular CSS format which the browser can read in the directory. In the below picture, you could see the changed css CSS style:

CSS of mixins.html

Figure 6. CSS of mixins.html.

Parametric Mixins

It is also possible to add parameters to enhance the utility of LESS by using the parameter mixins which takes arguments and its properties will appear only when mixed into another block.

Example

Create one html file as shown below:

Listing 4.mixin_parameters.html

<!doctype html>
<head>
<title>Mixins Example</title>
<link rel="stylesheet/less" href="mixin_style1.less" type="text/css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/less.js/2.0.0/less.min.js"></script>
</head>
<body>
	<h2>Parametric Mixins</h2>
	<div>This is the example of mixins parameters.</div>
</body>
</html> 

The less file can be created with styles as below: mixin_style1.less

.gradients (@background){  
    background: linear-gradient(top, @background, #DFB51D);  
    background: -o-linear-gradient(top, @background, #DFB51D);   
    background: -ms-linear-gradient(top, @background, #DFB51D);   
    background: -moz-linear-gradient(top, @background, #DFB51D);   
    background: -webkit-linear-gradient(top, @background, #DFB51D);   
}    
div {  
    .gradients(#DA4476); 
}

The code has a variable called “@background” which provides parameters to our mixins and contains different styles for displaying the output. We are using that variable instead of hard coded values. We have passed the parameter called “background” to the gradients class which includes some CSS styles as specified in the code. The div element is used in the html file which contains styles by mixing the class “.gradients” which is invoked in the div class as shown in the above code. If we want to provide different values, just simply provide variable value as parameter to your mixin.

When we run the program, we get the following output:

Output of mixin_parameters.html

Figure 7. Output of mixin_parameters.html.

We can see that how the .gradients class styles have been included in the div class by using parametric mixing as in below picture:

CSS of mixin_parameters.html

Figure 8. CSS of mixin_parameters.html.

Nesting

LESS allows using nesting of selectors inside other selectors which forms a group of another related code. With use of nested rules i.e. classes within classes, it reduces the use of repetitive code. Less allows nesting of CSS de instead of or in combination with cascading.

In CSS, we write every style which leads to long selectors that repeat the stuff again and again. For instance:

     .container h1{ }
     .container p{ }
     .container  .box  h1{ }
     .container  .box  p{ }

The problem here is, we are repeating our .container { } selector again and again and it consumes a lot of time. LESS allows clustering of rule set inside other rule set by reducing repetitive code. Simply put these children inside the .container { } parent and our code becomes as shown below:

.container{
   h1{}
   p{}
.box{
   h1{}
   p{}
}
}

Let’s see example of nesting which gives clear idea how actually it works:

Example

Create one html file as:

Listing 5.nesting.html

<!doctype html>
<head>
<title>Nesting Example</title>
<link rel="stylesheet/less" href="nesting_style.less" type="text/css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/less.js/2.0.0/less.min.js"></script>
</head>
<body>
	<div class="container">
	<h1>Header One</h2>
	<p>Less is cross browser friendly that allows developers to reuse CSS elements and write LESS code with the same semantics. </p>
	<p>Less allows variables to be defined. Less variables are defined with an at sign(@). </p>
	<div class="box">
	<h1>Header Two</h1>
	<p>Mixins allow embedding all the properties of a class into another class by including the class name as one of its properties.</p>
	</div>
	</div>
</body>
</html>

The nesting.less file can be written as shown below:

.container{
  h1{
       font-size: 25px;
       color:#E45456;
 	 }  
  	p{
       font-size: 25px;
       color:#3C7949;
  }
 .box{ 
 h1{
        font-size: 25px;
        color:#E45456;
  	 }   
  	 p{
       font-size: 25px;
       color:#3C7949;
  }
 }  
}

The above code is the same as earlier selector which we use in normal CSS for declaring values. But compared to that, this is easier to read and understand, and it takes up much less space. It simply puts our code snippet inside the parents. Now you don’t have to repeat selectors again and again. Simply nest the rule set inside another to indicate the hierarchy.

When we execute the above code, we get the following output:

 Output of nesting.html

Figure 9. Output of nesting.html.

The below picture shows, normal CSS rule set when we run the above nested code:

CSS of nesting.html

Figure 10. CSS of nesting.html.

Use nesting very effectively in a way that, you should not nest all your children selectors in single parent selector, it may become long chain as shown below:

.container  >  h1 > p > .box > h1 > p > …etc 

So it’s good practice to minimize your selector chain that is always readable and understandable. Generally it’s good practice to keep maximum chain of four selectors and not more than four selectors at all. So use nesting technique freely but with care as well.

Operations

Doing mathematical operations in your CSS in very helpful. LESS allows simple mathematical operations such as addition, subtraction, multiplication and division. Operations are very useful when we use variables which save a lot of time . LESS operations can be used to create complex relationships between properties. You can operate on any number, color or variable. We can use operations on numerical values like margins, heights, padding, font-sizes, color etc.

For instance:

@height: 50px;
.element1{
height: @height;
 }
.element2 {
 height: @height * 2;
}

Here, code uses multiplication operation to calculate height. We are assigning a value in to the @height variable. Next assigning this value to .element1 and to .element2, we are just multiplying height by 2 using asterisk (*) operator rather than calculating the height ourselves. If you change the value in the @height variable, then element2 will always have twice the height.

As we have stored a value, now we can use that variable to perform any operations such as addition, subtraction, and division. It will take numerical value and will operate accordingly.

Example

Create one html file:

Listing 6.operations.html

<!doctype html>
<head>
<title>Operations Example</title>
<link rel="stylesheet/less" href="operation_style.less" type="text/css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/less.js/2.0.0/less.min.js"></script>
</head>
<body>
	<p class="MyStyle">This is Example of Less Operation</p>

	<h2>Hello...Welcome to Less</h2>

	<h3>Hello...Welcome to Less</h3>

	<h4>Hello...Welcome to Less</h4>

	<p class="MyStyle1">This is Example of Less Operation</p>
</body>
</html>

Now, create less file as: operation_style.less

@color: #973B7D;
@size: 30px;

h2{
	font-size: @size + 5;
	color:@color;
}

h3{
	font-size: @size + 5 * 2;
	color:@color;
}

h4{
	font-size: @size / 2;
	color:@color;
}

.MyStyle {
	color: @color;
	font-size: @size * 1.5;
}

.MyStyle1 {
	color: @color;
	font-size: @size - 15;
}

The html file contains different types of statements with p, h2, h3, h4 tags. The CSS styles for all these tags are defined in the operation_style.less. In the less file, initially we have defined variables called @color and @size with the values. We are performing operations such as addition, subtraction, multiplication and division. Just notice that, we are simply putting value in a variable and performing all operations on a single variable until that makes your work easy.

The output of the above code looks like below:

Output of operations.html

Figure 11. Output of operations.html.

The normal css file look as shown below when we execute the above program.

 CSS of operations.html

Figure 12. CSS of operations.html.

Functions

Less functions allows one to one mapping with JavaScript code with the manipulation of values. Less comes with predefined functions which allow manipulating aspects of HTML elements in your style sheets.

Some of the math functions which LESS provides to operate on numerical values are:

  • round function,
  • floor function,
  • ceil function and
  • percentage function.

Less also provides use of color functions by providing functionality to increase or decrease lightness of colors, increase or decrease fadein, fadeout of colors and increase or decrease a color by specified number of degrees.

Usage of color functions

Darken Function:

Let’s take one variable for storing the value of the color green. It will look like the following:

@color: #7bab2e;

If you want to dark this color, instead of using hex value for that color we can simply use darken function to dark the color. Suppose you want to darken the @color by 15% of its initial value; then we will write the code shown below:

.box .darken{
background-color: @color;
border: 2px solid darken (@color, 15% )
}

Example

Listing 7. color_function.html

<!doctype html>
<head>
<title>Color Function Example</title>
<link rel="stylesheet/less" href="color_style.less" type="text/css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/less.js/2.0.0/less.min.js"></script>
</head>
<body>
<h2>Welcome</h2>
</body>
</html>

Create .less file as: color_style.less

@color: #cccccc;
@color1: #7bab2e;

h2{
           display:inline-block;
           width:100px;
           height:100px;
           background:@color;
    	margin:20px;
    	border: 3px solid darken(@color1, 20%); 
}

The above code includes CSS styles for output to be displayed. The LESS file uses darken function to make the border color darker and we will darken the @color by 205 of its initial value.

When we execute the above code, it results in the following output:

Output of color_function.html

Figure 13. Output of color_function.html.

Lighten Function:

Suppose you want to make lighter color than darker, just replace the darken word with lighten word in the above code. The html file is same and a bit has changed in the LESS file as shown below:

color_style.less

@color: #cccccc;
@color1: #7bab2e;;
h2{
           display:inline-block;
           width:100px;
            height:100px;
           background:@color;
    	margin:20px;
    	border: 3px solid lighten(@color1, 20%); 
}

The output will look like the following:

 Output of color_function.html

Figure 14. Output of color_function.html.

Mixing Colors

Less allows mixing the colors by using the mix () function, which generates output that results from the mixing of two colors. Let’s create an example by using mix() as shown below:

Listing 8. color_function.html

<!doctype html>
<head>
<title>Color Function Example</title>
<link rel="stylesheet/less" href="color_style2.less" type="text/css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/less.js/2.0.0/less.min.js"></script>
</head>
<body>
    <h2>Welcome</h2>
</body>
</html> 

color_style2.less

@blue: #0000FF;
@yellow:#FFFF00;
h2{
	 display:inline-block;
            width:100px;
            height:100px;
     	background-color: mix(@blue, @yellow, 30%);  
    	margin:20px;   	
}

This function takes three parameters, the first two parameters are color combination and last parameter is the weight of each colors. The parameters @blue and @yellow represent the green color. If we set the weight to 0%, this will result in the first color we stated and for 100%, it will do the opposite.

It displays the following output:

 Output of color_function.html

Figure 15. Output of color_function.html.

Conclusion

In this article, we have seen the power of using LESS for better management and usage of style sheets. The LESS preprocessor shares a lot of basics. It is a great tool for designers and developers to work more efficiently and quickly. In brief, it is fast, easy and modern way of writing and crafting CSS code. By using LESS, you will be creating and tweaking complex sheets faster and easier than even before. Source code of the examples is attached with this article. If you are using LESS for the first time, you may feel a little clumsy, but if you try it more often, it will surely become a lot easier. Hope you liked the article.

Links

Official Ember.js website

http://lesscss.org/


I''m a full stack developer with around 10+ yrs of experience. I enjoy writing technical articles on upcoming technical trends.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login