4

I'm trying to create a simple mixin in LESS for different colors I'll use for a website.

What i want is use mixin argument as a part of class name as well.

@green: #5FBEAA; // my color variable

.text-color(@color) {
    .text-{@color} {
        color: @color;
    }
}

.text-color(@green);

The output i'm getting is:

.text-#5FBEAA {
  color:#5FBEAA
}

What I want is:

.text-green {
  color:#5FBEAA
}
Deepak Yadav
  • 6,804
  • 5
  • 31
  • 49

2 Answers2

5

I think I have the solution using Variable Names.

Less

@green: #5FBEAA;

.text-color(@colorname) {
  @color: ~"@{colorname}";
  .text-@{color}{
    color: @@color;
  }
}

.text-color(green);

Output

.text-green {
  color: #5FBEAA;
}
  • Nice approach. Can you explain me, why we need to assign value to `@color` variable with `~@{colorname};` even if I write like this `@colorname;`, itl works. Is there any valid reason behind it? – Deepak Yadav Sep 12 '16 at 10:27
  • Can be replace `~"green"` by `green` in the call and looks better, I forgot to remove it after the tests I did. I have use `~@{colorname}` to get `green` as string. I edited the answer –  Sep 12 '16 at 10:35
2

I don't think its possible. The closest solution for this will be using an additional variable.

@green: #5FBEAA;
 .text-color(@name,@color) {
     .text-@{name} {
         color: @color;
     }
 }
 .text-color(green,@green);

This will compile to

.text-green {
  color: #5FBEAA;
}
Jinu Kurian
  • 9,128
  • 3
  • 27
  • 35