Skip to content

tip: scoping variables with & { ... } #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
maniqui opened this issue Aug 6, 2013 · 7 comments
Closed

tip: scoping variables with & { ... } #21

maniqui opened this issue Aug 6, 2013 · 7 comments

Comments

@maniqui
Copy link

maniqui commented Aug 6, 2013

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
    }
  }
}
@jonschlinkert
Copy link
Contributor

👍

@SomMeri
Copy link
Member

SomMeri commented Aug 8, 2013

👍 The best scoping trick so far

@jonschlinkert
Copy link
Contributor

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

@seven-phases-max
Copy link
Member

seven-phases-max commented Aug 30, 2013

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

@SomMeri
Copy link
Member

SomMeri commented Feb 15, 2015

It works also with import less/less.js#2442

@rodrigocarmine
Copy link

Thanks!!!

@postmeback
Copy link

postmeback commented May 8, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants