0
0
SASSmarkup~5 mins

Why custom functions are useful in SASS

Choose your learning style9 modes available
Introduction

Custom functions let you create your own reusable code pieces in Sass. They help you do tasks again and again without rewriting code.

When you want to calculate colors based on rules you decide.
When you need to repeat a math operation for sizes or spacing.
When you want to keep your styles consistent by reusing logic.
When you want to simplify complex style calculations.
When you want to make your code easier to read and maintain.
Syntax
SASS
@function function-name($parameter1, $parameter2) {
  @return value;
}
Use @function to start defining a custom function.
Always end the function with @return to send back a value.
Examples
This function doubles a number you give it.
SASS
@function double($number) {
  @return $number * 2;
}
This function creates a color from red, green, and blue values.
SASS
@function make-color($red, $green, $blue) {
  @return rgb($red, $green, $blue);
}
Sample Program

This example shows a custom function spacing that multiplies a number by 1.5rem. We use it to set padding and margin in a container. This keeps spacing consistent and easy to change.

SASS
@function spacing($factor) {
  @return $factor * 1.5rem;
}

.container {
  padding: spacing(2);
  margin: spacing(1);
  background-color: #eee;
}
OutputSuccess
Important Notes

Custom functions help keep your Sass code clean and DRY (Don't Repeat Yourself).

You can use any Sass features inside your functions, like math or color functions.

Remember to test your functions to make sure they return the right values.

Summary

Custom functions let you reuse code and calculations in Sass.

They make your styles easier to maintain and update.

Use them to keep your design consistent and your code clean.