Search code examples
sassmixinsextendsass-mapsscss-mixins

Passing multiple arguments in SASS Mixin to output set of classes or single class


$base-space: 1rem !default;

$space-map : (
    '1o9': $base-space,
    '1o8': $base-space/8,
    '1o4': $base-space/4,
    '1o2': $base-space/2,
) !default;

@mixin containers($new-space-map) {

    @each $name, $value in $new-space-map {

        .container--#{$name}{
            margin: $value 0;
        }
    }
}

@include containers($space-map);

This outputs 4 CSS classes.

I am trying to generate all 4 classes or only one class based on the name I pass as argument.

my output needs to be:

.container--1o9 {
  margin: 1rem 0;
}

.container--1o8 {
  margin: 0.125rem 0;
}

.container--1o4 {
  margin: 0.25rem 0;
}

.container--1o2 {
  margin: 0.5rem 0;
}

Or

.container--1o2 {
  margin: 0.5rem 0;
}

based on the argument I pass.

To explain further; I am trying trying to use @include on same SASS Map in both the ways mentioned below depending on my need:

@include containers(<SASS map file>); //This I achieved

or

@include containers(<any key from SASS Map>); //This I cant

I am stuck here and not sure if this is achievable or not. Any help will be very much appreciated.


Solution

  • Remove the !Default. This will work as you expect it to

    Link to sassmeister

    https://www.sassmeister.com/gist/2839eaf64bd441e73a92aed6bb980465

    Remember all 4 classes are being compiled into your CSS file. Just use the one you want