0
0
SASSmarkup~5 mins

Functions with parameters in SASS

Choose your learning style9 modes available
Introduction
Functions with parameters let you reuse code by giving inputs to get different results. This saves time and keeps your styles neat.
When you want to calculate colors based on different brightness levels.
When you need to create spacing sizes that change depending on input.
When you want to generate font sizes that scale with a factor.
When you want to reuse a style calculation but with different values each time.
Syntax
SASS
@function function-name($parameter1, $parameter2) {
  @return calculation or value;
}
Parameters are like placeholders for values you give when calling the function.
Use @return to send back the result from the function.
Examples
This function takes a number and returns its double.
SASS
@function double($number) {
  @return $number * 2;
}
This function lightens a color by a given amount.
SASS
@function color-brightness($color, $amount) {
  @return lighten($color, $amount);
}
This function returns spacing in rem units based on the factor.
SASS
@function spacing($factor) {
  @return $factor * 1rem;
}
Sample Program
This example defines a function that multiplies two numbers. Then it uses the function to set the width and height of a box in rem units.
SASS
@function multiply($a, $b) {
  @return $a * $b;
}

.box {
  width: multiply(5, 3) * 1rem;
  height: multiply(2, 4) * 1rem;
  background-color: #3498db;
}
OutputSuccess
Important Notes
Functions help keep your code DRY (Don't Repeat Yourself).
You can use built-in Sass functions inside your own functions.
Always return a value from your function using @return.
Summary
Functions with parameters let you reuse code with different inputs.
Use @function to define and @return to send back results.
Functions make your styles easier to maintain and change.