How to use Variables in LESS CSS?

- Andrés Cruz

En español
How to use Variables in LESS CSS?

If you have worked even a little with Cascading Style Sheets (CSS) it is very likely that you have done something like the following:

.clase1 {  
    background: #000;  
}  
.clase2 {  
    background: #FFF;  
    color: #000;  
}  
.clase3 {  
    border: 1px solid #000;  
	color: #F00; 
} 

Clearly, we see that there are repeated values throughout the CSS above; If we wanted to change (for example) the color black (#000) for some other color such as red (#F00) we would have to apply the change in three different places (for our example).

Las Variables en LESS CSS

Things get quite complicated when the Style Sheet grows and you would like to make a complete change to it; For this LESS CSS offers us the use of Variables.

Variables in LESS CSS work exactly like any variable in any programming language; that is, variables allow you to specify the values used in a single place and be able to use them throughout the Style Sheet. This has the advantage that global changes can be resolved as easily as changing a line of code; the value of the variable itself:

@color: #000;  
  
.clase1 {  
    background: @color;  
}  
.clase2 {  
    background: #fff;  
    color: @color;  
}  
.clase3 {  
    border: 1px solid @color;  
	color: #F00; 
} 

By compiling the previous LESS code we will obtain:

.clase1 {
  background: #000000;
}
.clase2 {
  background: #fff;
  color: #000000;
}
.clase3 {
  border: 1px solid #000000;
  color: #F00;
}

Variable Values in LESS CSS

We can define LESS CSS Variables with practically any value:

@color: 1px solid black;  
  
.clase1 {  
   border: @color;  
}  
.clase3 {  
  border: 1px solid @color;  
	color: #F00; 
} 

By compiling the previous LESS code we will obtain:

.clase1 {
  border: 1px solid #000000;
}
.clase3 {
  border: 1px solid 1px solid #000000;
  color: #F00;
}

Even text:

@contenido: "mi contenido";  
  
.clase1.before {  
  content: @contenido
} 

By compiling the previous LESS code we will obtain:

.clase1.before {  content: "mi contenido"; }

Variables as values for Variables in LESS CSS

It is also possible to define variables with a variable name:

@contenido: "mi contenido";  
@agregado: "contenido";
  
.clase1.before {  
  content: @@agregado;
} 

By compiling the previous LESS code we will obtain:

.clase1.before {
  content: "mi contenido";
}
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.