Search code examples
cssforeachsassmixins

SCSS Calling Mixin without duplication


I am looking to develop this mixin further, so I can pass multiple arguements through the mixin without having to re-create the include every time e.g:

NOT THIS:

@include main-container(red);
@include main-container(blue);

BUT THIS:

@include main-container(red, blue);

Current Code

@mixin main-container-bg($name){
    &.#{$name}-bg{
        background:url("/images/"#{$name}"-angle-bg.png") center 78px no-repeat;
    }
}

I believe I need a for statement alongside an each statement to loop my mixin though all of the arguments in the @include later in the scss.

Any idea's?

Any help is welcomed.

-Neil


Solution

  • You could use the @each directive and pass a list to the mixin in this way

    @mixin main-container-bg($listcolours) {
    
      @each $colour in $listcolours {
        &.#{$colour}-bg{
          background:url(/images/#{$colour}-angle-bg.png) center 78px no-repeat;
        }  
      }
    
    }
    
    
    div {
      @include main-container-bg((red, blue));
    }
    

    The generated CSS is

    div.red-bg {
      background: url(/images/red-angle-bg.png) center 78px no-repeat;
    }
    div.blue-bg {
      background: url(/images/blue-angle-bg.png) center 78px no-repeat;
    }