less-docs icon indicating copy to clipboard operation
less-docs copied to clipboard

tip: scoping variables with & { ... }

Open maniqui opened this issue 11 years ago • 6 comments

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
    }
  }
}

maniqui avatar Aug 06 '13 22:08 maniqui

:+1:

jonschlinkert avatar Aug 06 '13 22:08 jonschlinkert

:+1: The best scoping trick so far

SomMeri avatar Aug 08 '13 11:08 SomMeri

Yeah, it's pretty clean too. This doesn't feel hacky to me at all.

jonschlinkert avatar Aug 08 '13 13:08 jonschlinkert

+1. I usually call it "unnamed scope" technique.

seven-phases-max avatar Aug 30 '13 19:08 seven-phases-max

It works also with import https://github.com/less/less.js/issues/2442

SomMeri avatar Feb 15 '15 12:02 SomMeri

Thanks!!!

rodrigocarmine avatar Sep 23 '16 20:09 rodrigocarmine

In JS, we have let keyword which uses the similar concept of scoping.

postmeback avatar May 08 '23 06:05 postmeback