Mixin Parameters, Defaults, and Keyword Arguments
Mixins can accept positional parameters, default values, and keyword arguments. Parameters make a reusable pattern configurable without duplicating its implementation.
A parameter with a default value is optional. A caller can override that value by passing a positional or named argument.
Keyword arguments are especially useful when a mixin has several parameters because they make call sites self-documenting. Avoid overly generic mixins with many unrelated parameters; several small mixins are often easier to understand.
A Responsive Container Mixin
@mixin container(
$max-width: 72rem,
$gutter: 1rem
) {
width: min(calc(100% - 2 * #{$gutter}), #{$max-width});
margin-inline: auto;
}
.page-container {
@include container;
}
.article-container {
@include container($max-width: 48rem, $gutter: 1.5rem);
}💡 The mixin accepts a maximum width and horizontal gutter. The default call uses the default arguments, while the article container supplies custom values using keyword arguments.
The CSS
min() and calc() functions perform browser-side layout calculations. Sass interpolation is used to place the configured values into the CSS calculation.Knowledge Check
What is a major advantage of keyword arguments in a mixin with multiple parameters?