sass
  1. sass-functions

SASS Functions

Syntax

SASS functions are defined using the @function directive, followed by the function name, arguments and function body enclosed within curly braces. Here's an example of a SASS function:

@function add($a, $b) {
  @return $a + $b;
}

Example

Suppose we want to create a function that takes a color as an argument and returns a darker shade of that color. We can define the following SASS function:

@function darken-color($color, $percentage) {
  @return darken($color, $percentage);
}

Output

When we call the above function, it returns a darker shade of the given color based on the percentage provided as an argument.

$color1: #008080;
$color2: darken-color($color1, 10%);

The value of $color2 in this case will be #006d6d, which is the #008080 color darkened by 10%.

Explanation

SASS functions can accept any number of arguments, which are passed in as values when the function is called. A function must always contain a @return statement at the end, which specifies the value to be returned by the function.

In the example above, we created a function called darken-color which accepts two arguments - the color to be darkened and the percentage of darkness to be applied. We used the built-in darken() function provided by SASS to darken the color and returned the result using @return.

Use

SASS functions are useful when you want to automate repetitive tasks or calculations, and make your code more modular and reusable. Some common use cases for SASS functions include:

  • Calculating font sizes, margins, and padding based on a variable base value
  • Creating reusable color functions for color manipulation (e.g., lightening, darkening, or saturating a color)
  • Generating CSS rules based on arguments passed in as parameters

Important Points

  • SASS functions can accept any number of arguments and must contain a @return statement at the end.
  • SASS provides a set of built-in functions that can be used in your custom functions.
  • Use variables as function parameters to create reusable functions.
  • Functions can be called within other SASS functions, mixins, or properties.
  • SASS functions make your code more modular and easier to maintain.

Summary

SASS functions allow you to create custom functions that perform specific tasks or calculations, making your code more modular and reusable. They accept arguments, use variables, and return values using @return. SASS functions can be used for a variety of tasks, such as color manipulation, unit conversion, and generating CSS rules based on variables.

Published on: