Skip to content
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

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

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

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

maniqui opened this issue Aug 6, 2013 · 3 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
    }
  }
}
@lukeapage
Copy link
Member

Would be good to add to documentation.

@jonschlinkert
Copy link
Contributor

agreed, @maniqui can I get you to add this as an issue over here: https://github.com/less/less-docs/issues?state=open, so we can close this and keep that one open? I'll definitely add to docs. thanks

@maniqui
Copy link
Author

maniqui commented Aug 6, 2013

Done

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

3 participants