Frexuz
Frexuz

Reputation: 4933

SASS - Default values for variable arguments

Variable arguments was added in Sass 3.2.

@mixin hello($arguments...) {
    property: $arguments;
}

//Usage:
@include hello(1);
@include hello(1, 2, 3);
@include hello(1, 2);

However, this argument doesn't accept a default value, like so ($args...: default-value)

Right now, I'm using this code, but is there a better way?

@mixin transition($values...) {
    $values: null !default;

    @if $values == null {
        $values: all 0.3s ease;
    }

    -webkit-transition: $values;
    -moz-transition: $values;
    -ms-transition: $values;
    -o-transition: $values;
    transition: $values;
}

Upvotes: 5

Views: 3909

Answers (1)

Your solution does not work. When used with no arguments, e. g.

.foo { @include transition; }

the transition mixin returns an error:

() isn't a valid CSS value.

A variable argument can be treated as a list using the length() function. I suggest this solution:

@mixin transition($values...) {

  // Setting the default value
  @if length($values) == 0 {
    $values: all 0.3s ease;
  }

  -webkit-transition: $values;
  -moz-transition: $values;
  -ms-transition: $values;
  -o-transition: $values;
  transition: $values;
}

Demo: http://sassbin.com/gist/5867258/

PS all and ease are defaults, so the default value can be simplified to $values: 0.3s.

Upvotes: 8

Related Questions