Search code examples
csssasscompass-sassmixins

sass mixins with loops givies error


I'm writing a sass code to get css output as given below.

 background: -webkit-linear-gradient(top, 50%);
 background: -moz-linear-gradient(top, 50%);
 background: linear-gradient(top, 50%);

The sass mixin code i wrote for this is:

@mixin linear-gradient($name, $arg1, $arg2){
    @each $vendor in ('-webkit-', '-moz-','') {
        background: #{$vendor}#{$name}(#{$arg1}, #{$arg2});
    }
}
@include linear-gradient(linear-gradient, top, 50%);

But i was getting error. Can anyone tell why?


Solution

  • The $name parameter seems unnecessary so I've omitted it from my first example. The second example shows an alternative solution using $name so that it compiles the parentheses properly.

    @mixin linear-gradient($arg1, $arg2){
        @each $vendor in ('-webkit-', '-moz-','') {
            background: #{$vendor}linear-gradient(#{$arg1}, #{$arg2});
        }
    }
    
    @mixin linear-gradient($name, $arg1, $arg2){
        @each $vendor in ('-webkit-', '-moz-','') {
            background: #{$vendor}$name+'('+$arg1+', '+$arg2+')';
        }
    }
    
    #myElement {
        @include linear-gradient(top, 50%);
    }
    
    /* Output */
    
    #myElement {
      background: -webkit-linear-gradient(top, 50%);
      background: -moz-linear-gradient(top, 50%);
      background: linear-gradient(top, 50%);
    }