Sass @function Rule

Beginner
⏱️ 13 min read
📚 Updated: Jul 2026
🎯 5 Examples
@return · args…

What You’ll Learn

Sass @function lets you define complex operations on SassScript values and reuse them throughout your stylesheet. This page covers @return, arguments, defaults, keywords, argument lists, early returns, how functions differ from mixins, and five compiled examples.

01

Define

@function

02

Return

@return

03

Args

Required / optional

04

Keywords

$name: value

05

Rest

$args...

06

Practice

5 examples

What Are Sass Functions?

Official docs: functions allow you to define complex operations on SassScript values that you can re-use throughout your stylesheet. They make it easy to abstract out common formulas and behaviors in a readable way.

  • Defined with @function name($args…) { … }.
  • Called with normal CSS function syntax: rem(24px), sum(1px, 2px).
  • Must end with @return (the value used as the call result).
  • Names cannot begin with --.
  • Hyphens and underscores are identical: str-insert = str_insert.
  • Function names never appear in CSS—only the returned values do.
⚠️
Functions vs mixins

While it is technically possible for functions to have side effects (like setting global variables), that is strongly discouraged. Use mixins for side effects and CSS output; use functions just to compute values.

📝 Syntax

Write @function (<arguments…>) { … }. The body may contain universal statements (variables, control flow, other function calls) plus @return.

styles.scss
@use "sass:math";

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

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

📤 The @return At-Rule

Official docs: @return indicates the value to use as the result of calling a function. It is only allowed inside @function, and each function must end with a @return.

  • When @return is hit, the function ends immediately.
  • Early returns are great for edge cases without wrapping everything in @else.
  • You can have multiple @return paths; exactly one runs per call.

🔢 Arguments

Official docs: arguments let you customize a function each time it is called. Declare variable names in parentheses after the function name, then pass matching SassScript expressions when you call it.

Optional arguments

Give a default with $name: value. Callers can omit that argument. Defaults can be any expression and may refer to earlier arguments. Trailing commas in argument lists are allowed.

Keyword arguments

Pass by name: rem(8px, $base: 16px) or built-ins like color.scale($c, $lightness: 40%). Especially helpful for booleans and multiple optional values.

⚠️
Renaming args

Because any argument can be passed by name, renaming a parameter can break callers. Keep old names as optional aliases for a while if you must rename.

🔀 Taking Arbitrary Arguments

Official docs: if the last parameter ends in ..., extra positional arguments become a list (an argument list).

  • Pass a list with $list... to expand positional args.
  • Pass a map with $map... to expand keyword args.
  • Use meta.keywords($args) to read extra keyword arguments as a map.
  • Forward everything to another function with @return other($args...).
💡
Typo safety

If you never pass an argument list to meta.keywords(), that list will not allow extra keyword arguments—helping callers catch misspelled names.

📚 Other Functions

Besides your own @function rules, Sass ships a large built-in library (math, color, string, list, map, meta, and more). Host-language custom functions are also possible in Sass implementations. And any unknown call that is not a Sass function compiles to a plain CSS function.

styles.scss
// Unknown names become CSS (unless they use Sass-only arg syntax)
.card {
  background: var(--main-bg-color);
  background-image: radial-gradient(#f2ece4, #e1d7d2);
}
⚠️
Typo trap

Because unknown functions become CSS, a misspelled Sass helper may silently emit invalid CSS. Prefer namespaced module APIs and lint your compiled output.

📦 Functions With @use

In modern Sass, put helpers in a partial and load them with a namespace:

styles.scss
// _units.scss
@use "sass:math";

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

// style.scss
@use "units";

.title {
  font-size: units.rem(24px);
}

⚡ Quick Reference

GoalCode
Define@function rem($px) { @return …; }
Callfont-size: rem(24px);
Default arg@function rem($px, $base: 16px)
Keyword argrem(8px, $base: 16px)
Rest args@function sum($numbers...) { … }
Spread a listsum($widths...)
Early exit@if … { @return $x; }
From a moduleunits.rem(24px)

Examples Gallery

Each example defines and calls functions at compile time. Open View Compiled CSS for verified output.

📚 Getting Started

Reusable formulas that return values into CSS.

Example 1 — Basic Function

Compute a value with loops and lists, then use it in a property.

styles.scss
@use "sass:list";

@function fibonacci($n) {
  $sequence: 0 1;
  @for $_ from 1 through $n {
    $new: list.nth($sequence, list.length($sequence))
      + list.nth($sequence, list.length($sequence) - 1);
    $sequence: list.append($sequence, $new);
  }
  @return list.nth($sequence, list.length($sequence));
}

.sidebar {
  float: left;
  margin-left: fibonacci(4) * 1px;
}

How It Works

fibonacci(4) returns 5 at compile time. Multiplying by 1px gives a length for margin-left.

Example 2 — Optional & Keyword Args

Defaults fill missing values; keywords label what you override.

styles.scss
@use "sass:math";

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

.title {
  font-size: rem(24px);
  padding: rem(8px, $base: 16px);
}

How It Works

Omitting $base uses 16px. The keyword form makes the base explicit when you call rem(8px, $base: 16px).

📈 Color, Rest Args & Early Return

Flexible APIs for real design tokens and helpers.

Example 3 — Color Helper + Keywords

Custom hue invert plus a built-in keyword call from sass:color.

styles.scss
@use "sass:color";

@function invert-hue($color, $amount: 100%) {
  $inverse: color.adjust($color, $hue: 180deg);
  @return color.mix($inverse, $color, $amount);
}

$primary-color: #036;

.header {
  background-color: invert-hue($primary-color, 80%);
}

.banner {
  color: color.scale($primary-color, $lightness: 40%);
}

How It Works

invert-hue mixes a hue-shifted color with the original. color.scale(..., $lightness: 40%) shows named args on a built-in.

Example 4 — Argument Lists (...)

Accept any number of numbers, or spread a list into the call.

styles.scss
@function sum($numbers...) {
  $sum: 0;
  @each $number in $numbers {
    $sum: $sum + $number;
  }
  @return $sum;
}

$widths: 50px, 30px, 100px;

.micro {
  width: sum(50px, 30px, 100px);
  min-width: sum($widths...);
}

How It Works

Extra args land in $numbers. $widths... expands the list into the same positional call.

Example 5 — Early @return

Exit early for edge cases, then build the normal result path.

styles.scss
@use "sass:string";
@use "sass:meta";

@function str-insert($string, $insert, $index) {
  // Avoid extra work when the string is empty.
  @if string.length($string) == 0 {
    @return $insert;
  }

  $before: string.slice($string, 1, $index);
  $after: string.slice($string, $index + 1);
  @return $before + $insert + $after;
}

.probe {
  --early: #{meta.inspect(str-insert("", "Hi", 1))};
  --mid: #{meta.inspect(str-insert("Hello", "-", 3))};
}

How It Works

An empty string returns $insert immediately. meta.inspect prints the quoted string into a custom property so you can see the result in CSS.

🚀 Real-World Use Cases

  • Unit conversionrem(), fluid clamp helpers.
  • Design tokens — tint/shade, contrast, spacing scales.
  • Math helpers — ratios, Fibonacci-style sequences, clamp math.
  • String utilities — insert, strip, build class name fragments.
  • Library APIs — ship pure helpers via @use / @forward.

🧠 How Compilation Works

1

Define a function

Write arguments and one or more @return paths.

Source
2

Call it in a value

Use CSS function syntax inside properties or other expressions.

Compile
3

Evaluate to a value

Sass runs the body and substitutes the returned SassScript value.

Resolve
4

CSS ships

Browsers never see @function—only finished values.

⚠️ Common Pitfalls

  • Expecting CSS output — a function alone emits nothing; you must use its return value.
  • Side effects in functions — prefer mixins for writing styles or globals.
  • Missing @return — every path through a function must return.
  • Typo becomes CSS — unknown names pass through as plain CSS functions.
  • Confusing with mixins — no @include and no @content for functions.

💡 Best Practices

✅ Do

  • Keep functions pure—same inputs, same return value
  • Name them for intent (rem, sum, not helper1)
  • Use keyword args for optional knobs
  • Ship helpers through @use namespaces
  • Prefer built-in modules (sass:math, sass:color) when they fit

❌ Don’t

  • Use functions to emit CSS rules or set globals
  • Rename public args without a migration path
  • Rely on typo-to-CSS behavior for debugging
  • Duplicate built-ins you already get from the module system
  • Forget that browsers never see your function names

Key Takeaways

Knowledge Unlocked

Five things to remember about Sass functions

Define with @function, finish with @return, call like CSS.

5
Core concepts
📤 02

Return

@return value

Result
🔢 03

Args

defaults + keywords

API
🔀 04

Rest

$args… lists

Variadic
05

Pure

values, not CSS

Compute

❓ Frequently Asked Questions

A @function defines a reusable SassScript calculation. You call it with normal CSS function syntax, and it must end by returning a value with @return.
Functions compute and return values used in property values or other expressions. Mixins (@mixin / @include) insert styles (and can use @content). Official docs: use mixins for side effects; use functions just to compute values.
Yes. @return is only allowed inside @function, and each function must return a value. When Sass hits @return, the function ends immediately—useful for early exits.
Yes. Give defaults with $name: value, and call with keywords like rem(8px, $base: 16px). The last parameter can end in ... to accept an argument list.
Unknown calls compile to plain CSS functions (unless they use Sass-only argument syntax). That makes typos easy to miss—lint your CSS output or stick to namespaced module APIs.
Yes. Like other Sass identifiers, scale-color and scale_color refer to the same function.
Did you know?

Official Sass docs treat hyphens and underscores as the same in function names—so str-insert and str_insert call the same function.

Conclusion

@function is how you package reusable calculations in Sass. Keep helpers pure, return with @return, and load shared utilities through @use. Reach for mixins when you need to emit CSS.

Continue with @extend or browse @mixin / @include.

Next: Sass @extend

Inherit styles across selectors with placeholders and !optional.

@extend rule →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful