Jonathan Beebe
Jonathan Beebe

Reputation: 5226

How to define Sass mixins with variable arguments

In lesscss I can write mixins like this, such that calling .myMixin(@a) with one argument uses the first mixin, and calling it with two arguments .myMixin(@a, @b) uses the second version of the mixin.

.myMixin(@paramOne) {
  // do something with the single-parameter version of mixin
}

.myMixin(@paramOne, @paramTwo) {
  // do something with the two-parameter version of mixin
}

How can I do the same thing in sass? Or is there an even better way to accomplish this in the sass world?

Upvotes: 1

Views: 1541

Answers (1)

lefoy
lefoy

Reputation: 1178

You can set your second parameter to be false as the default value, and do a @if statement inside your mixin.

@mixin myMixin( $param1, $param2:false ){
    @if $param2 == false{
        // Do something
    }
    @else{
        // Do something with both parameters
    }
}

Edit: this a custom function I made to transform px unit into em unit. You can pass a list or a single value as parameter. You can also set a base and a line-height. Maybe you can find few tricks inside this function.

You can use it like this: emify(10px 16px, 16px).

This will output: 0.625em 1em

/**
*
* Emify
*    Transform px unit into em
* defaults:
*    base: 16
* usage:
*    emify(unit)
*    emify(unit, base)
*    emify(unit, line-height, base)
* examples:
*    emify(16px) = 1em
*    emify(16px, 10px) = 1.600em
*    emify(16px, 10px, 10px) = 1.600em / 1em
*
**/    
@function emify( $target, $lineheight: null, $base: null ) {

    @if $base == null and $lineheight == null { $base: 16 }
    @if $base == null and $lineheight != null { $base: $lineheight }

    [...]

}

Upvotes: 4

Related Questions