Functions can define complex operations on SassScript values that can be reused throughout the stylesheet. It makes it easier to abstract out the common formulas and behaviors in some readable way. Functions can be defined using @function at-rule.
Syntax:
html
A function name can be any Sass identifier. It must only contain universal statements, as well as the @return at-rule which indicates the value to use result of the function call. The normal CSS functions are used for calling functions.
Example:
html
Output:
html
Output:
@function <function name>(<arguments...>) {
...
}
@function power($base, $expo)
$result: 1
@for $_ from 1 through $expo
$result: $result * $base
@return $result
.sidebar
float: right
margin-left: power(6, 2) * 2px
.sidebar {
float: right;
margin-left: 64px;
}
Arguments: Arguments allow the function's behavior to be changed every time that they’re called. The arguments are specified in the @function rule after the function name as shown in the syntax. It is simply a list of variable names surrounded by parentheses or curly brackets. The functions are always called with the same number of arguments which are in SassScript expressions. The values of these expressions are available within the function body as the corresponding variables.
Types of arguments:
- Optional Arguments:
Example:
Output:html @function gfg($color, $amount: 100%) { $geeks: change-color($color, $hue: hue($color) + 180); @return mix($geeks, $color, $amount); } $primary-color: #ffffff; .header { background-color: gfg($primary-color, 80%); }.header { background-color: white; } - Arbitrary Arguments:
Example:
Output:html $lengths: 50px, 30px, 100px; .gfg { width: max($lengths...); }.gfg { width: 100px; } - Keyword Arguments:
Example:
Output:html $geeks: green; .banner { background-color: $geeks; color: scale-color($geeks, $lightness: +40%); }.banner { background-color: green; color: #1aff1a; }
@function add($numbers...) {
$add: 0;
@each $number in $numbers {
$add: $add + $number;
}
@return $add;
}
.gfg {
width: add(50, 30, 100);
}
.gfg {
width: 180;
}