Functions in SASS
In this lesson we will look at how to use functions. Functions are somewhat similar to mixins, but they allow you to add parameters that can change their values.
Let's make a function func that will set the font size. Let the size be passed as a parameter and the variable will act as a parameter:
$font-size: 10px;
Then we write the parameter $n into the function and be sure to specify @return in the function body:
@function func($n) {
@return $n * $font-size;
}
#main {
font-size: func(2);
}
Compilation result:
#main {
font-size: 20px;
}
You can also pass a named argument to the function. Let's rewrite the conditions of the previous example:
@function func($n) {
@return $n * $font-size;
}
#main {
font-size: func($n: 2);
}
And in the styles.css file we will see the same code:
#main {
font-size: 20px;
}
Tell me what the result of compiling the following code will be:
$size: 10px;
@function func($num) {
@return $num + $size;
}
div {
font-size: func(4);
}
Tell me what the result of compiling the following code will be:
$size: 4px;
@function func($num) {
@return $num + $size;
}
.card {
padding: func(2);
margin: func(6);
width: func(416);
}
Tell me what the result of compiling the following code will be:
$size: 2px;
@function func($num) {
@return ($num * $size) + 20;
}
.logo {
width: func(2);
height: func(4);
}