4

I've used guard expressions elsewhere in my CSS to achieve IF statements in LESS, however these don't work for me when trying to declare variables like so...

@neutral: false;
@warm: true;

when (@neutral = true) {
    @green: #91C95B;
    @red: #F15647;
    etc...
}
when (@warm = true) {
    @green: #91AD3C;
    @red: #BF2A23;
    etc...
}

This is an example of how I would like to be able to use that variable

h1 {
    color:@green;
}

This is how I would expect it to compile down to CSS

h1 {
    color: #91AD3C;
}

Is this possible with LESS or would I need to modify my code to use mixin guards?

1 Answer 1

5

You can use Guarded Mixins like this :

@neutral: false;
@warm: true;

.color() when (@neutral) {
    @green: #91C95B;
}
.color() when (@warm) {
    @green: #91AD3C;
}
.color();


h1 {
    color:@green;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this was exactly what I was looking for. I think the LESS documentation could do with some clarification as it isn't clear regarding this usage of mixin guards.
> I think the LESS documentation could do with some clarification - The documention is actually quite detailed on the guards stuff (Mixin Guards, CSS Guards). I guess what you're missing is actually variable scope info which is indeed not quite documented (except two minor sections: Scope, Mixins as Functions).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.