Search code examples
lessless-mixins

mixins with multiple params - how properties are selected?


I'm reading a manual on LESS and there is the following example here:

It is legal to define multiple mixins with the same name and number of parameters. Less will use properties of all that can apply. If you used the mixin with one parameter e.g. .mixin(green);, then properties of all mixins with exactly one mandatory parameter will be used:

.mixin(@color) {
  color-1: @color;
}
.mixin(@color; @padding:2) {
  color-2: @color;
  padding-2: @padding;
}
.mixin(@color; @padding; @margin: 2) {
  color-3: @color;
  padding-3: @padding;
  margin: @margin @margin @margin @margin;
}
.some .selector div {
  .mixin(#008000);
}

compiles into:

.some .selector div {
  color-1: #008000;
  color-2: #008000;
  padding-2: 2;
}

I can't seem to grasp the logic behind selecting the properties. Can someone please explain me it?


Solution

  • Quoting the LESS Manual:

    It is legal to define multiple mixins with the same name and number of parameters. Less will use properties of all that can apply. If you used the mixin with one parameter e.g. .mixin(green);, then properties of all mixins with exactly one mandatory parameter will be used

    The key statements are Less will use properties of all that can apply and then properties of all mixins with exactly one mandatory parameter will be used.

    In the below sample, the output contains both the properties specified within the .mixin with one parameter as well as the .mixin with two parameters because the .mixin with two parameters has a default value for the second one (and hence is in need of only one mandatory parameter).

    .mixin(@color; @padding:2) {
      color-2: @color;
      padding-2: @padding;
    }
    

    So in essence, when the second parameter is not specified in the mixin call statement, the rule/properties can still be applied because the default value would be used. If you remove the default value for the padding and make it like below, it would not get applied when the mixin call has only one parameter.

    .mixin(@color; @padding) {
      color-2: @color;
      padding-2: @padding;
    }
    

    Similarly, the .mixin with three parameters is not applied because the mixin call has only one parameter and there is a default value specified for only one other parameter. So in essence, we have only two parameters with values.

    .mixin(@color; @padding; @margin: 2) {
      color-3: @color;
      padding-3: @padding;
      margin: @margin @margin @margin @margin;
    }