Variables
A variable keeps a value under a name so you can use it many times: a colour, a size, a font. In Less a variable name starts with @ (in Sass with $). When the site's main colour changes, you edit one line instead of searching the whole project.
Declaring and using
A variable is declared like a CSS property: name, colon, value. Write in styles/main.less:
// styles/main.less
@primary: #2563eb;
@radius: 8px;
.btn {
color: white;
background: @primary;
border-radius: @radius;
}After compilation no variables remain — only their values:
.btn {
color: white;
background: #2563eb;
border-radius: 8px;
}Any CSS value works
A variable can hold a number with a unit, a colour, a string or a whole list of values:
// styles/main.less
@font-main: system-ui, sans-serif;
@shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
@gap: 16px;
.card {
padding: @gap;
font-family: @font-main;
box-shadow: @shadow;
}.card {
padding: 16px;
font-family: system-ui, sans-serif;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}<style>
.card {
padding: 16px;
font-family: system-ui, sans-serif;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
</style>
<div class="card">A card with a shadow</div>Scope
A variable declared at the top of the file is global: it is visible everywhere. A variable inside a rule is local: it exists only within that rule's braces and overrides a global one with the same name.
// styles/main.less
@gap: 16px;
.card {
@gap: 24px;
padding: @gap;
}
.alert {
padding: @gap;
}.card {
padding: 24px;
}
.alert {
padding: 16px;
}.card uses the local @gap, .alert the global one.
Lazy evaluation
Less first collects all variables of a scope and only then substitutes values. This is called lazy evaluation. Two rules follow from it: a variable can be used before it is declared, and if a name is declared twice, the last declaration wins.
// styles/main.less
.badge {
background: @accent;
}
@accent: #16a34a;
@accent: #f97316;.badge {
background: #f97316;
}The colour is orange: the line @accent: #f97316 comes later. This is how Bootstrap 3 themes work: you import its variables and declare your own below them — and they replace the values throughout the library. Sass works the other way round: the value is taken at the moment of use, and defaults need the !default flag.
Common mistake
Because of lazy evaluation you cannot "temporarily change" a variable in the middle of a file:
// styles/main.less
@size: 14px;
.small { font-size: @size; }
@size: 20px;
.large { font-size: @size; }.small {
font-size: 20px;
}
.large {
font-size: 20px;
}Both rules got 20px, because the last declaration applies to the whole scope. For different values use different variables: @size-small and @size-large.