less-docs
less-docs copied to clipboard
tip: scoping variables with & { ... }
Here is a trick I use to define variables and keep them in some private scope, avoiding them leaking to the global space.
& {
// Vars
@height: 100px;
@width: 20px;
// Don't define any prop:value on this scope (as doing so will generate (wrong) output).
.test {
height: @height;
width: @width;
}
}
.rest {
height: @height; // Name error: variable @height is undefined
}
Here, @height
and @width
are only defined for the scope created by & { ... }
You can also nest an scope inside a rule:
.some-module {
@height: 200px;
@width: 200px;
text-align: left;
line-height: @height; // 200px
& {
// Override original values
@height: 100px;
@width: auto;
.some-module__element {
height: @height; // 100px
width: @width; // 200px
}
.some-module__element .text {
line-height: (@height / 2); // 50px
}
}
& {
// Override original values
@height: 50px;
.some-module__another-element {
height: @height; // 50px
width: @width; // 200px
}
.some-module__another-element .text {
line-height: (@height / 2); // 25px
}
}
}
:+1:
:+1: The best scoping trick so far
Yeah, it's pretty clean too. This doesn't feel hacky to me at all.
+1. I usually call it "unnamed scope" technique.
It works also with import https://github.com/less/less.js/issues/2442
Thanks!!!
In JS
, we have let
keyword which uses the similar concept of scoping.