Simon
Simon

Reputation: 2986

How to pass a variable with arguments to a mixin?

Is it possible to have a variable (e.g. $args: 5vh, 10em, 25em) which can be passed as arguments to a mixin?

@mixin width($args...) {
  $props: (width, min-width, max-width);
  @for $i from 1 through length($args) {
      $val: nth($args, $i);

      @if $val != null {
        #{nth($props, $i)}: $val;
      }
  }
}

.el {
  @include width(5vh, 10em, 25em);
}

.ot {
  $args: 5vh, 10em, 25em;
  @include width($args);
}

The code above results in:

.el {
  width: 5vh;
  min-width: 10em;
  max-width: 25em;
}

.ot {
  width: 5vh, 10em, 25em;
}

Is there a way to "spread" the variable args so it gets interpreted as arguments in the mixin?

Upvotes: 0

Views: 53

Answers (1)

Grzegorz T.
Grzegorz T.

Reputation: 4113

Two ways

$style1: 100%,70px,#2c2c2c;
$style2: (background: #bada55, width: 100%, height: 100px);

@mixin box($width, $height, $background) {
  width: $width;
  height: $height;
  background-color: $background;
}

.test {
  @include box($style1...);
}

.test {
  @include box($style2...);
}

Upvotes: 1

Related Questions