0

I need to declare a LESS mixin with a variable number of arguments, and pass it to the mixin, like this:

.linear-gradient(@color1, @color2) {
    background: -webkit-linear-gradient(@color1, @color2); 
    background: -o-linear-gradient(@color1, @color2); 
    background: -moz-linear-gradient(@color1, @color2);
    background: linear-gradient(@color1, @color2); 
}

.linear-gradient(@color1, @color2, @color3) { ...
.linear-gradient(@color1, @color2, @color3, @color4) { ...

... // usage with a variable number of arguments: 
body > header {
    .linear-gradient(red, yellow, blue);

As described in the documentation I can use @arguments and @rest keywords, but is not very clear for me how exactly should it be used in my case...

Here is my PEN for testing

serge
  • 13,940
  • 35
  • 121
  • 205
  • @Harry: the OP of "duplicate" does not deal with `@arguments` I ask about – serge Oct 13 '15 at 10:57
  • 1
    Please check the answer posted by **esp**. The problem might be different but the solution is the same (you can see it in the answer posted here by Amit also). – Harry Oct 13 '15 at 10:58
  • @Harry: it may fit, however **esp** didn't mentioned the `;`detail – serge Oct 13 '15 at 11:11

1 Answers1

1

@rest is not a keyword, its a sample identifier use to demonstate .... It could have any other name.

To fix your code:

.linear-gradient(@rest...) {
    background: -webkit-linear-gradient(@rest); 
    background: -o-linear-gradient(@rest); 
    background: -moz-linear-gradient(@rest);
    background: linear-gradient(@rest); 
}

body > header {
    .linear-gradient(red, yellow, blue);
}

You could replace @rest with @arguments inside the mixin as you use the entire input as a "variable arguments list". Then you could also omit the @rest identifier altogether:

.linear-gradient(...) {
    background: -webkit-linear-gradient(@arguments); 
    background: -o-linear-gradient(@arguments); 
    background: -moz-linear-gradient(@arguments);
    background: linear-gradient(@arguments); 
}

There's no difference between the 2 versions.

But all of that is not what you want at all. The 2 solutions above will result in a CSS that looks like this:

background: linear-gradient(red yellow blue);

That is because the values are interpreted as individual arguments, and are concatenated in a string with spaces.

What you need is this:

.linear-gradient(@colors) {
    background: -webkit-linear-gradient(@colors); 
    background: -o-linear-gradient(@colors); 
    background: -moz-linear-gradient(@colors);
    background: linear-gradient(@colors); 
}

body > header {
    .linear-gradient(red, yellow, blue;);
}

This tells LESS that the argument passed into the mixin is a single variable, with comma's inside. That translates to your required output.

Amit
  • 45,440
  • 9
  • 78
  • 110