Arguing with Sass

I'm going to keep this short & sweet: keep your Sass mixins simple.

Given the syntax of Sass's Mixins, you're probably tempted to do something like the following:

@mixin box-shadow($inset:"", $color, $left, $top, $blur){
    box-shadow:$inset $color $left $top $blur;
}
.element{
    @include box-shadow("inset", black, 0, 0, 10px);
}

This is not how a box-shadow is usually written -- you don't need all those arguments separated by commas. A hugely simpler approach is to combine all the arguments into one $properties argument, then write the box shadow like you're used to. The only difference will be the @include mixin-name() syntax. How much cooler is our mixin now?

@mixin box-shadow($properties){
    box-shadow:$properties;
}
.element{
    @include box-shadow(inset black 0 0 10px);
}

Multiple Sass Mixin Arguments

Not only is this much cleaner, but we can now use unlimited mixin arguments if we want, like for multiple box-shadows. To do that, just include an ellipsis at the end of your mixin argument.

@mixin box-shadow($properties...){
    box-shadow:$properties;
}
.element{
    @include box-shadow(inset black 0 0 10px, black 0 0 10px, white 0 -10px 10px);
}

This makes way for some mega-powerful mixins that can box-shadow and linear-gradient anything its heart desires. Of course, be sure to include all the browser prefixes you need.

Mixin for Auto-Prefixing

A good way to abstract adding browser prefixes is to have a separate mixin.

@mixin prefixer($property, $value, $prefixes: webkit moz ms o) {
    @each $prefix in $prefixes {
        #{"-" + $prefix + "-" + $property}: $value;
    }
    #{$property}: $value;
}

Which can be used in other mixins...

@mixin box-shadow($properties...){
    @include prefixer(box-shadow, $properties);
}
Tweet