Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a property name as an argument to a mixin in less

I want to make a function/mixin that will make a color darker if it is already dark but lighter when it is light (normalize/extremeize?)

Is it possible to do this by passing a property name (color, background-color, border-right-color, etc)?

.normalize(@color, @amount, @prop: "color") when (lightness(@color) >= 50%)
{
    @prop:lighten(@color, @amount);
}
.normalize(@color, @amount, @prop: "color") when (lightness(@color) < 50%)
{
    @prop:darken(@color, @amount);
}
like image 315
Joe Flateau Avatar asked Dec 13 '22 02:12

Joe Flateau


2 Answers

This is currently a feature request on less.js github. So look out for it in less.js 1.4.. until then you can hack it like so...

.mixin(@prop, @value) {
    Ignore: ~"a;@{prop}:@{value}";
}

Not very nice and you get an extra property but its the only way at the moment.

like image 149
Luke Page Avatar answered Dec 14 '22 14:12

Luke Page


Guarded Mixins should be what you are looking for, however you can not use variables to define properties, only their values. So you can do it like this:

.normalize(@color, @amount) when (lightness(@color) >= 50%)
{
    color:lighten(@color, @amount);
}

.normalize(@color, @amount) when (lightness(@color) < 50%)
{
   color:darken(@color, @amount);
}

So this:

.class1 {
    .normalize(#ddd, 10%);
}

Will output this:

.class1 {
  color: #f7f7f7;
}

But you can not actually pass a property name as a variable. This is a limitation of LESS unfortunately, and while I've seen ways around it for things like margin direction, there is not a way to just pass any ol' property using a variable.

like image 24
Brian Hough Avatar answered Dec 14 '22 16:12

Brian Hough