Alex
Alex

Reputation: 929

Avoid repeat the same mixin in Sass

I have this Mixin for padding utility:

Sass code:

$padding: (
    top: "top",
    right: "right",
    bottom: "bottom",
    left: "left",
    all: "all"
);

@mixin no-padding($map) {
    @each $padding-side, $side in $map {
        @if $side == 'all' {
            & {
                padding: 0 !important;
            }
        } @else {
            &-#{$side} {
                padding-#{$side}: 0 !important;
            }
        }
    }
}

Use of it:

.u-noPadding {
   @include no-padding($padding);
}

I want to use the same Mixin but now for margin, is there any solution to avoid repeating the same mixin and make a good use of best practices?

Upvotes: 1

Views: 139

Answers (1)

Thielicious
Thielicious

Reputation: 4442

@mixin no($type,$sides:null) {
    $i:0 !important;
    @if $sides == null {
        #{$type}:$i;
    } @else {
        @each $side in $sides { 
            #{$type}-#{$side}:$i;
        }
    }
}

.u-noPadding {
    @include no(padding, top left etc...);        // choose any side separated with a space
}
.u-noMargin {
    @include no(margin);                          // instead of 'all', type nothing
}

Like this? Your $sides will be stored in a temporary map automatically if your second parameter is set, no need extra map for this. About the second parameter: If you want no sides, let it empty and all sides will have 0. Similiar to your 'all' idea.. it's shorter.

Upvotes: 1

Related Questions