Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 39 ยท Mixins and Functions

Writing Custom Sass Functions

Write custom Sass functions with @function and @return: px to rem conversion, default arguments, rest arguments, validation with @error and when to use a mixin instead.

A mixin outputs styles. A function outputs a value: a number, a color, a string, a list. You call it anywhere a value is allowed (width: rem(24px)), and Sass replaces the call with the result. Functions are how you encode design rules such as "all spacing is a multiple of 4", "convert pixels to rem" or "pick black or white text for this background".

@function and @return

SCSS
@function double($n) {
  @return $n * 2;
}

.box {
  width: double(30px);   // 60px
  padding: double(4px) double(8px);
}

The rules of a function:

  • It is declared with @function name($params) { ... }.
  • It must end by executing an @return, which stops the function and gives back the value. (A function that finishes without @return is an error.)
  • It cannot contain style rules or declarations; those belong in mixins.
  • Parameters work like mixin parameters: defaults, keyword arguments, rest arguments $args....

Function names, like variables, treat hyphens and underscores as the same character.

A classic: pixels to rem

Designers think in pixels and accessibility advice says to size text in rem, so that it follows the user's browser font setting. A function connects the two worlds:

SCSS
@use "sass:math";

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

h1 { font-size: rem(32px); }   // 2rem
p  { font-size: rem(18px); }   // 1.125rem

Dividing 32px by 16px cancels the units and leaves 2; multiplying by 1rem gives 2rem.

A rem() function

Spacing scales

Functions are excellent for design systems because they replace "magic numbers" with a rule:

SCSS
$space-unit: 4px;

@function space($steps) {
  @return $space-unit * $steps;
}

.card { padding: space(4); margin-bottom: space(6); }   // 16px, 24px

If the design team changes the base to 5px, change one line and every use updates. The function name also documents intent better than 16px scattered through the code.

Branching and validation

Functions can use @if / @else, loops and local variables. Use @error to stop compilation with a helpful message when the input is wrong:

SCSS
@function clamp-percent($value) {
  @if not math.is-unitless($value) and math.unit($value) != "%" {
    @error "clamp-percent expects a number or a percentage, got #{$value}";
  }
  @return math.max(0, math.min(100, $value));
}

@warn prints a message but continues; @error aborts. Both are explained in debugging with @warn, @error and @debug.

A contrast function and an error

The second call fails on purpose. Watching the error message is a good way to see how @error helps the next developer.

Rest arguments and lists

A function can accept any number of arguments with $args...:

SCSS
@use "sass:list";

@function sum($numbers...) {
  $total: 0;
  @each $n in $numbers {
    $total: $total + $n;
  }
  @return $total;
}

.grid { width: sum(10px, 20px, 30px); }   // 60px

(@each is covered in loops.) Remember that variables assigned inside an @each body update the outer $total; see the scope rules in Variables.

Recursion

Functions can call themselves. Use it for things like exponentiation by repeated multiplication or walking a nested map, but keep an exit condition:

SCSS
@function factorial($n) {
  @if $n <= 1 { @return 1; }
  @return $n * factorial($n - 1);
}

Functions versus mixins

Function Mixin
Result One value Declarations or rules
Used Inside a value With @include
Can contain declarations No Yes
Typical use Math, color picks, lookups Reusable styles

Rule of thumb: if you need a number, color or string, write a function; if you need CSS output, write a mixin.

Calling built-in functions

You have already used built-ins such as math.div and color.channel. Sass ships many, grouped in modules (sass:math, sass:color, sass:string, sass:list, sass:map, sass:selector, sass:meta). The next lessons cover color functions and math, string and list functions, and Built-in modules gives the full overview.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must every Sass function do before it ends?

    A function must return a value with @return. Reaching the end without one is an error.
  2. 2. Which can a function contain?

    Functions compute values. They can use logic, variables and loops, but not output styles.
  3. 3. What does @error do inside a function?

    @error aborts compilation. @warn is the one that continues.
  4. 4. What does rem(32px) return with @return math.div($px, 16px) * 1rem?

    32px divided by 16px gives the unitless 2, and multiplying by 1rem gives 2rem.

Summary

  • @function name($args) { @return value; } defines a function that returns one value.
  • Functions can have defaults, keyword and rest arguments, branches, loops and recursion.
  • They cannot output CSS; use mixins for styles.
  • @error and @warn help validate input.
  • Typical functions: rem(), space(), contrast pickers, token lookups.

Next: Built-in color functions