Sub topic 8
Mixins, arguments and @content
A mixin is a named block of Sass that you write once and insert wherever you need it. This chapter covers defining mixins, passing arguments in several ways, and wrapping caller-supplied styles with @content. It assumes you can write CSS rules and media queries, and that you know Sass variables and nesting with & from earlier chapters.
What a mixin does
You define a mixin with @mixin and insert it with @include. Sass copies the mixin's body into the rule that includes it, so the compiled CSS has no trace of the mixin itself.
@mixin visually-hidden {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.skip-link {
@include visually-hidden;
}Compiled output:
.skip-link {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}Each @include produces its own copy of the declarations. Ten includes mean ten copies. This is the main difference from @extend, which is covered in a later chapter.
A mixin can also contain whole style rules, nested selectors and media queries. If you include it at the top level of a file, it emits those rules directly. If you include it inside a rule, nested selectors resolve against that rule.
Arguments
Parameters go in parentheses after the mixin name. Give a parameter a default with a colon, and the caller may omit it.
@mixin button-base($bg, $color: white, $radius: 4px) {
padding: 0.5rem 1rem;
background: $bg;
color: $color;
border-radius: $radius;
}
.btn {
@include button-base(#3366cc);
}
.btn-danger {
@include button-base($bg: #cc3333, $radius: 0);
}Compiled output:
.btn {
padding: 0.5rem 1rem;
background: #3366cc;
color: white;
border-radius: 4px;
}
.btn-danger {
padding: 0.5rem 1rem;
background: #cc3333;
color: white;
border-radius: 0;
}The second include uses keyword arguments. You name each argument, so you can skip $color and the order no longer matters. Prefer keyword arguments once a mixin has more than two parameters, because @include button-base(#cc3333, white, 0) is hard to read at the call site.
Rules to remember:
- Required parameters (no default) must come before optional ones if you pass arguments by position.
- A default can refer to an earlier parameter, for example
$hover-bg: darken($bg, 10%). That works only with a function from a module you have loaded, so check the module is available. - Leaving out a required argument is a compile error, not an empty value.
Variable arguments
A parameter ending in ... collects any number of remaining arguments into a list. This suits properties that take comma-separated values.
@mixin shadow($layers...) {
box-shadow: $layers;
}
.panel {
@include shadow(0 1px 2px rgba(0, 0, 0, 0.2), 0 4px 8px rgba(0, 0, 0, 0.1));
}The output is box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2), 0 4px 8px rgba(0, 0, 0, 0.1);.
You can also spread a list or a map into an include with .... A map spreads as keyword arguments, and its keys must be unquoted names that match parameter names.
$danger-button: (
bg: #cc3333,
radius: 2px
);
.btn-alert {
@include button-base($danger-button...);
}This is useful when your design tokens already live in maps.
Passing a block with @content
@content marks a slot inside a mixin. Whatever block the caller writes after @include is inserted there. This lets a mixin own the wrapper (a media query, a pseudo-class, a selector context) while the caller supplies the declarations.
@mixin respond($min) {
@media (min-width: $min) {
@content;
}
}
.nav {
display: block;
@include respond(48rem) {
display: flex;
}
}Compiled output:
.nav {
display: block;
}
@media (min-width: 48rem) {
.nav {
display: flex;
}
}Sass bubbles the media query out of .nav and re-wraps the declarations in .nav. You write the breakpoint once in the mixin, and a change there updates every caller.
A mixin can use @content more than once. The caller's block is then copied at each slot.
Passing arguments to the content block
@content can hand values back to the block. The caller receives them with using.
$breakpoints: (
sm: 40rem,
md: 48rem
);
@mixin each-breakpoint($map) {
@each $name, $width in $map {
@media (min-width: $width) {
@content($name);
}
}
}
.grid {
@include each-breakpoint($breakpoints) using ($name) {
&::after {
content: "#{$name}";
}
}
}Compiled output:
@media (min-width: 40rem) {
.grid::after {
content: "sm";
}
}
@media (min-width: 48rem) {
.grid::after {
content: "md";
}
}The number of values passed by @content(...) must match the using (...) list, or Sass reports an error.
Scope of the content block
The block is evaluated where the caller wrote it, not inside the mixin. It can see the caller's variables. It cannot see variables local to the mixin unless they arrive through @content(...).
@mixin tinted {
$tint: #eef;
@content;
}
.a {
@include tinted {
background: $tint; // Error: undefined variable
}
}Fix this by passing the value: @content($tint) in the mixin and using ($tint) at the call.
Mixins compared with functions and @extend
| Tool | Returns | Output | Use it when |
|---|---|---|---|
| Mixin | Nothing | Declarations or rules, copied per include | You need to emit CSS, possibly with a wrapper |
| Function | One value | A value inside a declaration | You compute a length, color or string |
| `@extend` | Nothing | Selector grouping, no copying | Several selectors share an identical, fixed set of styles |
If you find yourself writing a mixin that only contains @return-style logic, write a function. If a mixin takes no arguments and is included in many places, consider a placeholder with @extend to avoid repeating the output.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Undefined mixin` | Mixin defined in another file that was not loaded, or a typo | Load the file with `@use` and include as `namespace.name` |
| `Missing argument $x` | A required parameter was omitted | Pass it or add a default |
| `Mixin doesn't accept a content block` | The caller wrote `{ ... }` but the mixin has no `@content` | Add `@content` to the mixin or remove the block |
| `No argument named $x` | A keyword name does not match any parameter | Check the spelling, because names include the `$` |
| `Undefined variable` inside a content block | The block used a mixin-local variable | Pass the value through `@content(...)` and `using` |
| Large CSS output | A big mixin is included many times | Move shared parts to a placeholder, or reduce the mixin |
When a mixin lives in a module loaded with @use, include it through the namespace, as in @include layout.respond(48rem). The module system is covered in a later chapter.
Exercises
Exercise
Write a mixin named truncate that takes an optional $lines argument, defaulting to 1. When $lines is 1, it should emit single-line truncation (overflow: hidden; text-overflow: ellipsis; white-space: nowrap;). When it is greater than 1, it should emit multi-line clamping (display: -webkit-box; -webkit-line-clamp: $lines; -webkit-box-orient: vertical; overflow: hidden;). Then include it in .title with no argument and in .summary with three lines.
Show answer
@mixin truncate($lines: 1) { @if $lines == 1 { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } @else { display: -webkit-box; -webkit-line-clamp: $lines; -webkit-box-orient: vertical; overflow: hidden; } } .title { @include truncate; } .summary { @include truncate(3); }
Exercise
A mixin on-hover contains &:hover { @content; }. A teammate's block inside it refers to a variable $shade that is declared inside the mixin, and compilation fails with an undefined variable error. Explain why, and give two lines of change that fix it.
Show answer
The content block is evaluated in the caller's scope, so mixin-local variables are invisible to it. Change the mixin to @content($shade); and change the include to @include on-hover using ($shade) { ... }.