Less Variables

This chapter explainsÂ about the Less Variables, its types and how Â to set string as Variables.

Similar to the standard programming language, LESS can also create variables. The colors, dimensions, font size, etc. can be changed and each variable is defined with (@) symbol in the beginning and (:) colon at the end.

Below is theÂ code for .less and .css, which define two variables. One is for background color and the other is for text color.

LESS code

@background-color: #FF0040;
@text-color: #190707;
p{
background-color: @background-color;
color: @text-color;
padding: 20px;
}
ul{
background-color: @background-color;
}
li{
color: @text-color;
}


CSS code

p{
background-color:#FF0040;
color: #190707;
padding: 20px;
}
ul{
background-color: #FF0040;
}
li{
color: #1A237E;
}


Variables

The following are some of the variables of LESS.

Setting strings as variables

Similar to JavaScript and PHP, set strings to variables isÂ very important in using icon font for web designing. Below code explains how to set variables as strings and .less to .css compilation process.

.less file

@name: "SPLessons";
@description: "The best tutorial website";
a:before {
content: @description;
}


After compiling, the above code automatically generates the below CSS code.

.css file

a:before {
content: "The best tutorial website";
}


Below example explains the use of variables in LESS.
The conceptual figure explains the overall concept of converting .less to .css.
Create a .html file and .lessÂ in Nodejs folder as shown below.

.html file

<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css">
<title>LESS variables overview</title>
<h1>Welcome to SPLessons</h1>
<div class="div1">
<p>Faster maintenance can be achieved by using variables.</p>
</div>
<div class="div2">
<p>One can make coding faster and save the time by using the LESS operations.</p>
</div>
</body>
</html>


.less file

@primarycolor: #2E2EFE;
@color1: #81F7F3;
h1 {
color: @primarycolor;
}
.div1{
background-color : @color1;
}
.div2{
background-color : @color1;
}


Compile .less to .css by using the following command.

lessc style.less style.cs

By compiling the above code, the converted .css file looks like as shown below.

.css file

@primarycolor: #2E2EFE;
@color1: #81F7F3;
h1 {
color: @primarycolor;
}
.div1{
background-color : @color1;
}
.div2{
background-color : @color1;
}


OnceÂ the required changes are done, run the html file in a browserÂ to get theÂ following output.

Summary

• The variables like size, color, etc. can be created or changed, similar to a standard programming language.
• Strings can be set as variables and are defined with symbols in the beginning and at the end.

• Make sure the variables are defined with the @ symbol.
• Create both the HTML and Less files in Node js folder.
• Compile less to css before running the application.