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

4

4

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);
}
Necessaries answered 21/5, 2012 at 16:41 Comment(0)
I
11

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.

Ironworker answered 22/5, 2012 at 4:8 Comment(1)
And use an intermediate variable to use the darken function.Ironworker
W
2

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.

Wear answered 21/5, 2012 at 17:59 Comment(0)
Y
0

In the corresponding issue on Less' GitHub there is a workaround suggested by cloudhaed:

.blah ()      { color: black }                 // All blahs
.blah(right)  { padding-right: 20px }          // Right blahs
.blah(left)   { padding-left: 20px }           // Left blahs

@side: left;
.class { .blah(@side) }

Output

.class { color: black; padding-left: 20px;}

Maybe this will do?

Year answered 7/8, 2014 at 8:6 Comment(0)
W
0

This feature was added since v1.6.0:

@property: color;

.widget {
  @{property}: #0ee;
  background-@{property}: #999;
}

Compiles to:

.widget {
  color: #0ee;
  background-color: #999;
}

See http://lesscss.org/features/#variables-feature-properties

Weald answered 8/6, 2019 at 21:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.