Sass offers functions and mixins that accept parameters. You can use Sass default parameters, that is, parameters that have a value even if you don’t provide them when the function or mixin is called.

Let’s focus on mixins here. Here’s the syntax of a mixin:

@mixin foo($a, $b, $c) { // I can use $a, $b, and $c in here, but there is a risk they are null
} .el { @include foo(1, 2, 3); // if I tried to do `@include foo;` // ... which is valid syntax... // I'd get `Error: Missing argument $a.` from Sass
}

It’s safer and more useful to set up default parameters in this Sass mixin:

@mixin foo($a: 1, $b: 2, $c: 3) {
} .el { // Now this is fine @include foo; // AND I can send in params as well @include foo("three", "little", "pigs");
}

But what if I wanted to send in $b and $c, but leave $a as the Sass default parameter? The trick is that you send in named parameters:

@mixin foo($a: 1, $b: 2, $c: 3) {
} .el { // Only sending in the second two params, $a will be the default. @include foo($b: 2, $c: 3);
}

A real-life example using Sass default parameters

Here’s a quick-y mixin that outputs what you need for very basic styled scrollbars (Kitty has one as well):

@mixin scrollbars( $size: 10px, $foreground-color: #eee, $background-color: #333
) { // For Google Chrome &::-webkit-scrollbar { width: $size; height: $size; } &::-webkit-scrollbar-thumb { background: $foreground-color; } &::-webkit-scrollbar-track { background: $background-color; } // Standard version (Firefox only for now) scrollbar-color: $foreground-color $background-color;
}

Now I can call it like this:

.scrollable { @include scrollbars;
} .thick-but-otherwise-default-scrollable { // I can skip $b and $c because they are second and third @include scrollbars(30px);
} .custom-colors-scrollable { // I can skip the first param if all the others are named. @include scrollbars($foreground-color: orange, $background-color: black);
} .totally-custom-scrollable { @include scrollbars(20px, red, black);
}

I’m just noting this as I had to search around a bit to figure this out. I was trying stuff like sending empty strings or null as the first parameter in order to “skip” it, but that doesn’t work. Gotta do the named parameter approach.

Similar Posts