Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Functions

A function takes values, calculates something and returns one value with @return. A mixin inserts declarations; a function is used inside a value, like width: rem(24px). Functions are handy for repeated calculations: converting units, building a spacing scale.

Your first function

Functions are kept with the other tools in styles/abstracts/. Create styles/abstracts/_functions.scss with a function that converts pixels to rem:

// styles/abstracts/_functions.scss
@use "sass:math";
 
@function rem($pixels) {
  @return math.div($pixels, 16px) * 1rem;
}

math.div(24px, 16px) gives the plain number 1.5 — the pixels cancel out — and multiplying by 1rem adds the unit.

Calling a function

A function is called like a CSS function, through the module's namespace:

// styles/components/_cards.scss
@use "../abstracts/functions";
 
.card {
  padding: functions.rem(24px);
  font-size: functions.rem(18px);
}
// styles/main.scss
@use "components/cards";
.card {
  padding: 1.5rem;
  font-size: 1.125rem;
}

In the browser 1.5rem grows when the reader increases the font size in the settings — that is why sizes are written in rem, and the function lets you think in pixels from the design.

Arguments with default values

As in mixins, arguments can have defaults and can be passed by name. Add a spacing scale to the same file: step 1 is 4px, step 2 is 8px, and so on:

// styles/abstracts/_functions.scss
@function space($step, $base: 4px) {
  @return $step * $base;
}
// styles/components/_buttons.scss
@use "../abstracts/functions";
 
.btn {
  padding: functions.space(2) functions.space(4);
  margin-right: functions.space($step: 3, $base: 5px);
}
// styles/main.scss
@use "components/buttons";
.btn {
  padding: 8px 16px;
  margin-right: 15px;
}

All gaps on the site come from one scale, so they stay consistent.

Function or mixin?

FunctionMixin
Declared with@function@mixin
Used withA call inside a value: space(2)@include
Gives backOne valueDeclarations and rules

If you need a number, a colour or a string — write a function. If you need lines of CSS — a mixin.

Common mistake

A function must reach @return. If you forget it — for example, write the calculation but not the return — Sass stops with the error Function finished without @return. Also note that a function may not output declarations: color: red; inside @function is an error. Everything a function does ends with one @return.

Thanks for reading!

Donate to the site — we work hard for you.