2

I'd like to define a global LESS variable depending on a class that is applied to the <body>.

Is this possible with LESS?

Here is my mixin:

.dynamic-colors(@color) {

    //set my variable
    @c-dynamic: @color;

    //I can use my variable here
    .something {
        color: @c-dynamic;
    }
}

body.colors--black {
    .dynamic-colors(#000000);
}

body.colors--red {
    .dynamic-colors(#ff0000);
}

.something-else {
    //this returns undefined because @c-dynamic
    //was only defined inside of .dynamic-colors()
    color: @c-dynamic;
}

I believe @c-dynamic will be limited to the scope of the .dynamic-colors mixin.

Is there any way I can set the variable to be global?

Michael Lynch
  • 2,682
  • 3
  • 31
  • 59
  • Well, no, it can't work that way. Less code is compiled with no knowledge of your HTML so you can't use a HTML stuff ("body class") as a *condition* for variable values. In other words if you want `.something-else` to have different colors to apply depending on different body classes you also need to define multiple `.something-else` rulesets (e.g. `.colors--black .something-else`, `.colors--red .something-else` etc.). – seven-phases-max Sep 09 '14 at 20:37
  • Or yet in another words, note that in your snippet its *two* `@c-dynamic` variables defined unconditionally. So if you make them global only one of them (the last one) will have an effect regardless of body class in HTML. – seven-phases-max Sep 09 '14 at 20:40
  • For possible approaches see http://stackoverflow.com/a/15368587 and similar Q/A found with http://stackoverflow.com/search?tab=relevance&q=%5bless%5d%20theme – seven-phases-max Sep 09 '14 at 20:49

1 Answers1

1

So to not leave this one without an answer. You can define global variable with a mixin just by invoking that mixin in the global scope, e.g.:

.dynamic-colors(@color) {
    @c-dynamic: @color;
}

.dynamic-colors(#123); // expose @c-dynamic into global scope

div {
   color: @c-dynamic; // -> #123
}

But (as mentioned in comments above) this does not look like something you really mean to get in the end. You can't make this (or any other) variable value to depend on a body class since at the time of compilation Less has no knowledge of the HTML you're going to apply the generated CSS to.

seven-phases-max
  • 11,765
  • 1
  • 45
  • 57