Home > other >  Less OR operator
Less OR operator

Time:10-18

Is it possible to have fallback variable if other is 'undefined'. As in the following example:

@defColor = '#fff';
@setColor = '';

.selector {
   color: @setColor || @defColor;
}

For which the above case should return:

.selector {
   color: #fff;
}

And when setColor is not empty, it will use it:

@defColor = '#fff';
@setColor = '#000';

.selector {
   color: @setColor || @defColor;
}

Which will return:

.selector {
   color: #000;
}

I know the following will work:

.selector {
   color: @defColor;
   color: @setColor;
}

But it looks wrong.

Thanks!

CodePudding user response:

I think this should work using LESS's logical if (documentation) and iscolor (documentation) functions:

@defColor: #fff;
@setColor: '';

.selector {
   color: if(iscolor(@setColor), @setColor, @defColor);
}

It's worth noting that "#fff" is interpreted as a string not a color, so you need to leave out the quotation marks when defining your color variables for this method to work.

You can paste this into LESS's playground to try it out.

  • Related