romuleald
romuleald

Reputation: 1434

less css avoid globalized variable

I'm looking for the best way to avoid globally diffused variables.

I made a test with this configuration:

_import.less

@test: #FFF;

_import2.less

@test: #000;

test.less

@import (reference) "_import";

body {
    background: @test;
}

test2.less

@import (reference) "_import2";

div {
    background: @test;
}

index.less

@import "test";
@import "test2";

The output with lessc index.less test.css still looks like

body {
  background: #000;
}
div {
  background: #000;
}

But what I'm looking for is:

body {
  background: #FFF;
}
div {
  background: #000;
}

Using less 2.7 or 3.9 give the same behavior.
Do someone know a solution?
Thanks

Upvotes: 0

Views: 57

Answers (1)

seven-phases-max
seven-phases-max

Reputation: 11820

You can always isolate the scope of anything (incl. an imported file) using "unnamed namespace", i.e. & {}, block.

E.g.:

test.less:

@import "_import";

body {
    background: @test;
}

test2.less:

@import "_import2";

div {
    background: @test;
}

index.less:

& {@import "test";}
& {@import "test2";}

Depending on your goals these & {} blocks can be moved right into the test files themselves.

---

Ref: Local Variable Scoping in Import Files

Upvotes: 2

Related Questions