Skip to content

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

Closed

Description

@maniqui

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

  1. jonschlinkert commented on Aug 6, 2013

    @jonschlinkert
    Contributor

    👍

  2. SomMeri commented on Aug 8, 2013

    @SomMeri
    Member

    👍 The best scoping trick so far

  3. jonschlinkert commented on Aug 8, 2013

    @jonschlinkert
    Contributor

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

  4. seven-phases-max commented on Aug 30, 2013

    @seven-phases-max
    Member

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

  5. SomMeri commented on Feb 15, 2015

    @SomMeri
    Member

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

  6. rodrigocarmine commented on Sep 23, 2016

    @rodrigocarmine

    Thanks!!!

  7. postmeback commented on May 8, 2023

    @postmeback

    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions