2

Is it possible to assign a variable based on another variable using less css?

pseudo code:

@userpick = red; /* this changes based on user pick */

@color1 = red;
@color2 = blue;

if( @userpick == @color1)
  @systempick = @color2
else( @userpick == @color2)
  @systempick = @color1    

I want to be able to use @systempick as a color value not as a css style. For example:

border: 5px dashed @systempick;

3 Answers 3

4

Doesn't use a mixin, but resolves your desire

If the @userpick is stored as a string instead, then that could be used to access another variable name based off of it (a variable variable), like so:

LESS

@userpick: "blue"; /* this changes based on user pick, saved as a string */
@setopposite: "@{userpick}-opp";

//set opposing values
@red-opp: blue;
@blue-opp: red;

@systempick: @@setopposite;

.test {
  color: @systempick;
}

CSS Output (note how blue outputs #ff0000, i.e. red)

/* this changes based on user pick */
.test {
  color: #ff0000;
}

Since you are dealing with colors, the @userpick needs to be saved as a string because otherwise, LESS will automatically assign it a hex value rather than the color name.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use guards in mixins to change the color that is used, e.g.

.a when (@userpick = @color1) {
  color: @color2;
}

.a when (@userpick = @color2) {
  color: @color1;
}

You might get code duplication but its the only way to get an if statement.

Other ways are possible (e.g. inline javascript if using less.js or a function plugin if using dotless) but are probably a little hacky.

1 Comment

The problem with using this solution is that the duplication may not be manageable when using many colors on different styles. I've posted an updated solution. Thanks for your suggestion.
0

I was able to get what I needed, however this may not work on the PHP port of Less. This was a bit tricky since you can assign variables only once. There are also some restrictions regarding scope of variables. I'm also comparing color values using HSV (hue, saturation, value)

.set_colors(#F00, #00F, #F00); /* pass red, blue and user pick */

.set_colors(@c1, @c2, @u) when (hue(@c1) = hue(@u)) and  (saturation(@c1) = saturation(@u)) and  (lightness(@c1) = lightness(@u)){
    @color1 = @c1;
    @color2 = @c2;
    @userpick = @c1;
    @systempick = @c2;
} 
.set_colors(@c1, @c2, @u) when (hue(@c2) = hue(@u)) and  (saturation(@c2) = saturation(@u)) and  (lightness(@c2) = lightness(@u)){
    @color1 = @c1;
    @color2 = @c2;
    @userpick = @c2;
    @systempick = @c1;
} 

Comments

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.