skip to content

In Sass, when do you write a @mixin with @content rather than a @function, and what can each one produce?

level: middleimportance: should knowfreq 13%

answer

  1. values versus styles
  2. @return ends every function
  3. @include drops in declarations
  4. @content injects the caller's block
  5. unknown names pass through as CSS

basics

~20 s

A @function computes a value and hands it back with @return; it cannot emit declarations or rules. A @mixin, pulled in with @include, emits styles, and @content lets the caller pass a block the mixin wraps, such as a media query.

solid answer

~40 s

Use a **function** when you need a value: `@function to-rem($px)` runs its body (variables, `@if`, `@each`, `@error`) and must end in `@return`, and its result goes wherever an expression can (`gap: to-rem(24px)`). Style rules, CSS at-rules, `@include` and declarations are not allowed inside one. Use a **mixin** when you need styles: `@include` copies its declarations and nested rules into the current context, and it takes arguments with defaults and keywords like a function. `@content` marks where a block passed by the caller is injected; the classic case is `@include above(md) { … }` wrapping the caller's styles in a `@media` rule. The content block is lexically scoped: it sees the caller's variables, not the mixin's, unless the mixin passes them with `@content(...)` and the caller accepts them with `using (...)`.

code

scss · 21 lines
scss
@use "sass:map";
@use "sass:math";

$breakpoints: (sm: 36rem, md: 48rem, lg: 64rem);

@function to-rem($px, $base: 16px) {
  @return math.div($px, $base) * 1rem;
}

@mixin above($name) {
  @media (min-width: map.get($breakpoints, $name)) {
    @content;
  }
}

.course-list {
  gap: to-rem(24px);
  @include above(md) {
    grid-template-columns: repeat(2, 1fr);
  }
}

go deeper

for a junior

Recall that functions return values with @return and mixins emit styles through @include. Be able to write a breakpoint mixin that wraps @content in a media query.

for a middle

Explain what each body may contain, how defaults, keyword and arbitrary arguments work, and how @content is scoped, including passing arguments with @content and using.

for a senior

Catch the silent failures: a misspelt function passing through as plain CSS, side effects hidden in a function, or a library mixin whose content-block arguments became a breaking change.

for a principal

Decide what a shared library exposes: a few value functions and documented mixins form an API you can version; dozens of overlapping mixins do not.

## Two kinds of reusable code Sass offers two ways to package logic for reuse, and they answer different needs. A **function** produces a *value* (a length, a colour, a list) that is used inside an expression. A **mixin** produces *styles* (declarations and whole rules) that are dropped into the stylesheet where it is included. Choosing between them is mostly a matter of asking what you need back. ## Functions: values only A function is defined with `@function name($args...) { … }` and called with ordinary CSS function syntax. - Its body may contain only **universal statements**: variable declarations, flow control (`@if`, `@each`, `@for`, `@while`) and `@error`, `@warn` and `@debug`. - It must end with **`@return`**, which supplies the call's result. - It **cannot** contain style rules, CSS at-rules such as `@media`, `@include`, or declarations; nothing inside it produces CSS. - It may technically change global variables, but the Sass docs strongly discourage side effects: use mixins for those and functions to compute values. - Arguments work as they do for mixins: defaults (`$base: 16px`), keyword arguments, and `$args...` for any number of arguments. A call that names neither a user-defined nor a built-in function is not an error: Sass compiles it as a **plain CSS function**, passing the arguments through. That keeps new CSS functions working, but it also means a misspelt helper is copied into the CSS silently. ## Mixins: styles, arguments and @content A mixin is defined with `@mixin` and used with `@include`: 1. `@include` copies the mixin's declarations and nested rules into the current context; a mixin can also be included at the top level to emit whole rules. 2. Arguments may be required, optional with defaults, passed by keyword, or collected with `...`. 3. **`@content`** marks where a block written by the caller is injected: in `@include above(md) { … }`, the braces' contents are passed into the mixin. 4. A mixin may contain several `@content` rules; the block is included separately at each. 5. The content block is **lexically scoped**: it sees variables where the `@include` is written, not variables defined inside the mixin. A mixin passes values explicitly with `@content($value)`, and the caller receives them with `@include name using ($value) { … }`. When a mixin puts a `@media` rule inside a style rule, as a breakpoint mixin included in `.course-list` does, Sass swaps the two so the output has the media query at the top level with the selector inside it. ```scss @use "sass:map"; @use "sass:math"; $breakpoints: (sm: 36rem, md: 48rem, lg: 64rem); @function to-rem($px, $base: 16px) { @return math.div($px, $base) * 1rem; } @mixin above($name) { @if not map.has-key($breakpoints, $name) { @error "Unknown breakpoint `#{$name}`."; } @media (min-width: map.get($breakpoints, $name)) { @content; } } ``` ## Generating classes with @each and @if Control flow is where mixins and functions meet data. `@each $key, $value in $map` assigns each key and value in turn, and interpolation (`#{…}`) puts the key into a selector: ```scss $status-colors: (open: #2e7d32, waitlist: #f9a825, closed: #c62828); @each $status, $color in $status-colors { .badge--#{$status} { background: $color; } } ``` `@if` and `@else` choose branches, and `@error` stops compilation with a message. In a mixin that is how you reject a breakpoint name missing from the map instead of emitting a broken media query. ## Choosing between them | Need | Use | Why | |---|---|---| | A computed length, colour or list | `@function` | Returns a value usable in any expression | | A bundle of declarations | `@mixin` | Copies styles into the including rule | | Wrap the caller's styles in a media query or selector | `@mixin` with `@content` | Injects the caller's block at a chosen point | | Validate an input | Either, with `@error` | Fails the build with a clear message | ## Pitfalls interviewers probe - Expecting a function to emit `color: red`: it cannot, because declarations are not allowed in a function body. - Expecting a content block to read the mixin's local variables: it cannot without `@content(...)` and `using`. - Trusting the compiler to catch a misspelt function name: the call passes through as plain CSS. - Adding arguments to `@content(...)` in a shared library: every caller's `using` list must accept them, so it is a breaking change, and passing a single map is the more flexible design.

  • A Sass stylesheet calls `to-rme(24px)` instead of the user-defined `to-rem(24px)`. Why does the build succeed?
    Any call that is neither a user-defined nor a built-in Sass function is compiled as a plain CSS function, so `to-rme(24px)` is written into the output unchanged and the browser then ignores the invalid declaration. Sass does this so new CSS functions work without a Sass release; the cost is that such typos must be caught by reviewing or testing the compiled CSS.
  • Why can't a content block read a variable the mixin defines?
    Content blocks are lexically scoped: they see variables where the `@include` is written, not those inside the mixin. To hand data to the block, the mixin writes `@content($value)` and the caller declares `@include name using ($value) { … }`. Passing an extra argument later breaks every caller, so a map is the flexible choice.
  • How would you generate a `.badge--open`, `.badge--closed` class per status from a Sass map?
    Loop over the map with `@each $status, $color in $status-colors`, where the key goes to the first variable and the value to the second, and interpolate the key into the selector: `.badge--#{$status} { background: $color; }`. Wrapping the loop in a mixin that takes the map lets several stylesheets reuse it.

  • A Sass function can output declarations when it is called inside a rule.
  • A content block can read the local variables of the mixin it is passed to.
  • Calling an undefined Sass function always fails the build.
  • Mixins cannot take default or keyword arguments; only functions can.
  • A mixin may contain only one @content rule.