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 } } } ```
Activity
jonschlinkert commentedon Aug 6, 2013
👍
SomMeri commentedon Aug 8, 2013
👍 The best scoping trick so far
jonschlinkert commentedon Aug 8, 2013
Yeah, it's pretty clean too. This doesn't feel hacky to me at all.
seven-phases-max commentedon Aug 30, 2013
+1. I usually call it "unnamed scope" technique.
SomMeri commentedon Feb 15, 2015
It works also with import less/less.js#2442
rodrigocarmine commentedon Sep 23, 2016
Thanks!!!
postmeback commentedon May 8, 2023
In
JS, we haveletkeyword which uses the similar concept of scoping.