Computer Magic Logo
Variables

Sunday, June 7, 2015

Published by Aristotelis Pitaridis

The variables in a programming language is very useful because it allows us to customize easily large pieces of code. Exactly the same can be done with Less. For example, if a color is used too many times, and later you want to change this color, it will make things really difficult to find all the places where you used this color. With less you can store the color in a variable and instead of using the color you can use the variable. This way you can easily change the color later simply by modifying the value that we have stored in the variable.

Below we can see how we can declare and use a variable to a less file:

@gray: #CCCCCC;

#header{
    background-color: @gray
}
#footer{
    background-color: @gray
}

The result of the above code after compilation can be seen below:

#header {
    background-color: #cccccc;
}
#footer {
    background-color: #cccccc;
}

In Less we can use the name of a variable to refer to it. Below we can see an example.

@mainColor: red;
@bgColor: 'mainColor';
background-color: @@bgColor;

The result of the above code is the following:

background-color: red;