Custom Functions

Write functions that compute and return a single value.

Syntax@function name($args) { @return value; }

A function computes and returns a value with @function and @return. The difference from a mixin: a mixin outputs declarations, a function returns a value you use inside a declaration.

Functions are ideal for calculations you repeat, like converting pixels to rem or reading from a design-token map.

Example

Example · css
@use 'sass:math';

$base: 16px;

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

.title {
  font-size: rem(24px);   // 1.5rem
  margin-bottom: rem(8px); // 0.5rem
}

When to use it

  • A developer writes a rem() function that converts pixel arguments to rem values, used consistently across all typography and spacing declarations.
  • A design system provides a z() function that looks up layer names in a map, preventing z-index collision by centralizing the layer registry.
  • A team creates a contrast() function that returns black or white depending on a background color's luminance, automatically ensuring readable text.

More examples

Simple px-to-rem function

A custom function converts pixel values to rem using safe division from sass:math, with 16 as the default base font size.

Example · css
@use 'sass:math';

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

h1 { font-size: rem(32); }
p  { font-size: rem(14); }
.small { font-size: rem(12); }

Map lookup function

Wraps map.get() in a function that validates the key and throws an error on typos, making z-index management safe.

Example · css
@use 'sass:map';

$z-layers: (base: 0, dropdown: 100, modal: 200, toast: 300);

@function z($layer) {
  @if not map.has-key($z-layers, $layer) {
    @error 'Unknown z-layer: #{$layer}';
  }
  @return map.get($z-layers, $layer);
}

.modal { z-index: z(modal); }

Function with guard and @return

Builds a fluid type clamp() value from min and max pixel inputs, with an @error guard ensuring valid argument order.

Example · css
@function clamp-rem($min-px, $max-px) {
  @if $min-px > $max-px {
    @error '$min-px must be less than $max-px';
  }
  @return clamp(#{$min-px}px, 4vw, #{$max-px}px);
}

h1 { font-size: clamp-rem(24, 48); }

Discussion

  • Be the first to comment on this lesson.