SyntaxStudy
Sign Up
SASS / SCSS Writing Custom @function Definitions
SASS / SCSS Beginner 1 min read

Writing Custom @function Definitions

SASS allows you to define custom functions with `@function` and return values with `@return`. A function takes zero or more arguments, performs a calculation, and returns a single value — a number, string, color, list, or map. Custom functions are called just like built-in SASS functions, by name with parentheses, and can be used anywhere a CSS value is expected. Functions differ from mixins in an important way: functions compute and return a value, while mixins output CSS declarations. Use a function when you need to calculate a dimension, derive a color, or look up a value from a map. Use a mixin when you want to output a block of CSS rules or properties. SASS includes a rich set of built-in functions for color manipulation (lighten, darken, saturate, mix), string operations (to-upper-case, str-slice), list operations (nth, length, append), and math (percentage, round, ceil, floor, abs). Custom functions build on top of these to create domain-specific utilities tailored to your design system.
Example
// ── Custom @function examples ─────────────────────────────────────────────────

@use 'sass:math';
@use 'sass:string';

// Convert pixels to rem based on a configurable base font size
$base-font-size: 16px;

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

// Convert pixels to em based on a parent size
@function em($px, $parent: 16px) {
    @return math.div($px, $parent) * 1em;
}

// Clamp a value between a min and max
@function clamp-value($value, $min, $max) {
    @return min(max($value, $min), $max);
}

// Build a CSS custom property reference string
@function token($name) {
    @return var(--#{$name});
}

// Determine whether text on a given background should be light or dark
@function contrast-color($bg, $light: #fff, $dark: #222) {
    $lightness: lightness($bg);
    @return if($lightness > 50%, $dark, $light);
}

// ── Using the functions ───────────────────────────────────────────────────────

h1 { font-size: rem(36px); }   // → 2.25rem
h2 { font-size: rem(28px); }   // → 1.75rem
p  { font-size: rem(16px); }   // → 1rem

.caption { font-size: em(13px, 16px); }  // → 0.8125em

$brand: #3498db;

.badge {
    background: $brand;
    color     : contrast-color($brand);  // #fff (brand is dark enough)
    padding   : rem(4px) rem(10px);
    border-radius: rem(12px);
}