Sub topic 9
Writing your own functions
A Sass function takes values in and returns one value. This chapter covers how to define functions, how arguments work, how to validate input, and where functions go wrong. It assumes you can already write variables, mixins and @use, and that you know basic CSS units. Basic sass:math usage is a plus.
Functions and mixins
Both are reusable blocks with arguments, but they produce different things.
| Row | Function | Mixin |
|---|---|---|
| Called with | Its name inside a value, such as `rem(24)` | `@include name` |
| Produces | One value, through `@return` | Declarations or whole rules |
| Can output CSS | No | Yes |
| Typical use | Unit conversion, lookups, color math | Media queries, repeated blocks of properties |
If the result goes on the right-hand side of a property, write a function. If it emits CSS, write a mixin.
Defining a function
A function is @function, a name, an argument list, and a body that ends in @return.
@use 'sass:math';
@function rem($px, $base: 16) {
@return math.div($px, $base) * 1rem;
}
.title {
font-size: rem(24);
}This compiles to:
.title {
font-size: 1.5rem;
}math.div(24, 16) is the unitless number 1.5. Multiplying by 1rem gives it a unit. Use math.div and not the / operator, because slash division is deprecated.
@return ends the function immediately. A function that finishes without reaching @return is a compile error.
Arguments
Defaults and keyword arguments
A parameter with a default, like $base: 16, is optional. Callers can pass arguments by position or by name.
@use 'sass:math';
@function rem($px, $base: 16px) {
@return math.div($px, $base) * 1rem;
}
.lead {
font-size: rem(30px, $base: 20px);
}rem(30px, $base: 20px) returns 1.5rem. Keyword arguments make calls readable when a function has several optional parameters. They also let you skip an optional parameter in the middle of the list.
Rest arguments
A final parameter ending in ... collects all remaining arguments into a list.
@function sum($numbers...) {
$total: 0;
@each $n in $numbers {
$total: $total + $n;
}
@return $total;
}
.box {
width: sum(10px, 20px, 5px);
}The result is width: 35px;. The same syntax works at the call site. If $sizes is a list, sum($sizes...) passes each element as a separate argument.
Variables created inside a function are local. Assigning to $total here does not change any global $total.
Validating input
Without checks, bad input produces confusing output far from the cause. The first rem above breaks if someone passes 24px. math.div(24px, 16) is 1.5px, and multiplying by 1rem yields the invalid unit px*rem. A defensive version checks units first.
@use 'sass:math';
@function rem($px, $base: 16px) {
@if math.is-unitless($px) {
$px: $px * 1px;
}
@if math.unit($px) != 'px' {
@error "rem() expects pixels, got `#{$px}`.";
}
@return math.div($px, $base) * 1rem;
}
.title {
font-size: rem(24);
}
.sub {
font-size: rem(18px);
}Both rem(24) and rem(18px) work. A call like rem(2em) stops compilation with the message from @error. Dividing px by px leaves a unitless number, so * 1rem gives the right unit.
Sass has two diagnostic directives:
@errorstops compilation. Use it when continuing would produce wrong CSS.@warnprints a message and continues. Use it for deprecated or suspicious input.
Functions that read maps
Functions pair well with maps. A lookup function can be stricter than a bare map.get, which returns null for a missing key and lets the problem slip into the output.
@use 'sass:map';
$spacing: (
sm: 0.5rem,
md: 1rem,
lg: 2rem
);
@function space($key) {
@if not map.has-key($spacing, $key) {
@error "Unknown spacing key `#{$key}`. Available: #{map.keys($spacing)}.";
}
@return map.get($spacing, $key);
}
.card {
padding: space(md);
margin-bottom: space(lg);
}This compiles to padding: 1rem; margin-bottom: 2rem;. A call such as space(xl) fails with a message listing sm, md, lg. The function reads $spacing from the file's top level. If the map lives in another file, load it with @use and read it through its namespace, such as tokens.$spacing.
A function can also return a list, a map, a string or a color, not only a number.
Gotchas
Misspelled names pass through silently
If no Sass function has the called name, Sass treats the call as a plain CSS function and writes it unchanged. This is how calc(), var() and rgb() keep working. It also means a typo is not an error:
.title {
font-size: rme(24);
}This compiles to font-size: rme(24);. The browser then ignores the declaration. When a value comes out of the compiler looking like your source, check the spelling and check that the module defining the function was loaded with @use.
Names collide with built-ins and CSS
A function you define with the same name as a global Sass or CSS function takes precedence in your code. That can confuse readers and break calls that expected the original. Choose distinct names. In a shared codebase, prefer descriptive names such as rem or space, and load functions through namespaced modules so each call shows where it came from.
Functions cannot emit CSS
Declarations, rules and @include are not allowed in a function body. Only the value passed to @return leaves the function.
Functions should be pure
A function that returns the same output for the same input is easy to test and reason about. Avoid reading or changing global variables inside functions. With @use, you can only assign to a module's variable through its namespace, and keeping that rare keeps the function predictable.
Testing a function
Put a function in a partial and compile a scratch file that calls it. For example, create _tokens.scss with your functions and scratch.scss:
@use 'tokens';
.test {
a: tokens.rem(24);
b: tokens.space(md);
}Compile it with sass scratch.scss and read the printed CSS. The property names a and b are throwaway, because the goal is to see the computed values.
Exercise
What does this code compile to, and why does it fail or succeed? @function double($n) { $result: $n * 2; } .a { width: double(10px); }
Show answer
It fails to compile. The function body never reaches an @return, so no value is produced and Sass reports that the function finished without @return. Adding @return $result; fixes it, and the output becomes width: 20px;.
Exercise
Write a function clamp-between($value, $min, $max) that returns $min if $value is below it, $max if $value is above it, and otherwise $value. Then give the compiled result of width: clamp-between(120px, 50px, 100px);.
Show answer
@function clamp-between($value, $min, $max) {
@if $value < $min {
@return $min;
} @else if $value > $max {
@return $max;
}
@return $value;
}
The call returns 100px, because 120px is greater than the maximum, so the second branch returns $max. The compiled line is width: 100px;.