DanMad
DanMad

Reputation: 1755

Appending a value in Sass

I am working with BEM and Sass, using the following @mixin:

@mixin modifier($modifiers...) {
  $result: '';

  @each $modifier in $modifiers {
    $result: append($result, '#{&}--#{$modifier}');
  }

  @at-root #{$result} {
    @content;
  }
}

This function usually handles a single modifier (i.e. foo--bar). But I have tried to construct it so if there is ever a scenario where two modifiers compounded elicits a unique behaviour. This is why the @mixin can handle multiple arguments if necessary.

The problem is the unexpected behaviour resulting when I pass two arguments. Consider the following:

.foo {
  display: block;

  @include modifier('bar', 'baz') {
    display: none;
  }
}

The intended output is as follows:

.foo {
  display: block;
}
.foo--bar.foo--baz {
  display: none;
}

However, it seems a space is added when I append items and so .foo--baz is actually treated as a descendant of .foo--bar, as with the following example:

.foo {
  display: block;
}

.foo--bar .foo--baz {
  display: none;
}

How do I prevent $result from adding spaces between each append()?

Thanks in advance!

Upvotes: 2

Views: 1809

Answers (1)

Arkellys
Arkellys

Reputation: 7790

I managed to get the output you want by using string concatenation instead of the append() function:

@mixin modifier($modifiers...) {
   $result: '';

   @each $modifier in $modifiers {
      $result: '#{$result}#{&}--#{$modifier}';
   }

   @at-root #{$result} {
      @content;
   }
}

Upvotes: 4

Related Questions