0
0
SASSmarkup~5 mins

Function definition with @function in SASS

Choose your learning style9 modes available
Introduction

Functions let you reuse code by creating small blocks that return values. This helps keep your styles neat and easy to change.

When you want to calculate colors or sizes dynamically.
When you need to reuse a calculation in many places.
When you want to keep your code organized and avoid repeating yourself.
When you want to create custom values based on inputs.
When you want to make your styles easier to maintain.
Syntax
SASS
@function function-name($parameter1, $parameter2, ...) {
  @return value;
}

The @function keyword starts the function.

Use @return to send back the result.

Examples
This function doubles the input number.
SASS
@function double($number) {
  @return $number * 2;
}
This converts pixels to rem units assuming 16px base font size.
SASS
@function make-rem($pixels) {
  @return $pixels / 16 * 1rem;
}
This adds two numbers and returns the sum.
SASS
@function add($a, $b) {
  @return $a + $b;
}
Sample Program

This example defines a function to calculate spacing by multiplying a factor by 8 pixels. Then it uses the function to set padding and margin in a container.

SASS
@function calculate-spacing($factor) {
  @return $factor * 8px;
}

.container {
  padding: calculate-spacing(3);
  margin: calculate-spacing(2);
  border: 1px solid black;
}
OutputSuccess
Important Notes

Functions must always return a value using @return.

You can use functions inside property values to keep your CSS flexible.

Function names should be descriptive to make your code easier to read.

Summary

@function creates reusable code blocks that return values.

Use @return to send back the result from the function.

Functions help keep your styles clean, organized, and easy to update.