SASS functions

Sass Functions allow you to define complex calculations and transformations that can be used throughout your stylesheet.

What are SASS functions?

Functions are a powerful feature in SASS that allow you to perform complex operations on values, manipulate data, and generate content dynamically. SASS functions can be used to perform arithmetic operations, manipulate colors, work with strings, and more.

Functions in SASS are similar to functions in programming languages, but they can be used within SASS stylesheets to generate CSS code dynamically.

Using Built-in Functions

SASS provides a variety of built-in functions that you can use to perform operations like math, color manipulation, string manipulation, and more. Here are some examples of built-in functions and how to use them.

Math Functions

SASS provides a number of math functions that allow you to perform arithmetic operations on values. Here are some examples:

.round(1.2);          // returns 1
.ceil(1.2);           // returns 2
.floor(1.2);          // returns 1
.abs(-1.2);           // returns 1.2
.min(1, 2, 3);        // returns 1
.max(1, 2, 3);        // returns 3
.random(1, 100);      // returns a random number between 1 and 100

Color Functions

SASS provides a variety of color functions that allow you to manipulate colors. Here are some examples:

.lighten(#007fff, 20%);       // returns a lighter shade of blue
.darken(#007fff, 20%);        // returns a darker shade of blue
.opacify(#007fff, 0.2);       // makes the color more opaque
.transparentize(#007fff, 0.2); // makes the color more transparent
.mix(#007fff, #ff0000, 50%);  // returns a mix of two colors

String Functions

SASS provides a variety of string functions that allow you to manipulate strings. Here are some examples:

.to-upper-case("hello world");  // returns "HELLO WORLD"
.to-lower-case("HELLO WORLD");  // returns "hello world"
.str-index("hello world", "world"); // returns the index of the first occurrence of "world"
.str-insert("hello", " world", 5);  // inserts " world" into "hello" at position 5

Creating Custom Functions

In addition to using built-in functions, you can also create your own functions in SASS using the @function directive. Functions take input values, perform calculations, and return a result. Here's an example of a simple function that calculates the area of a rectangle:

@function rectangle-area($width, $height) {
  @return $width * $height;
}

// Usage:
$area: rectangle-area(10px, 20px); // Returns 200px

Custom functions can be very powerful, and can be used to create reusable pieces of code that can be used throughout your stylesheets.

Conclusion

SASS functions are a powerful feature that allow you to perform complex operations on values, manipulate data, and generate content dynamically. By using built-in functions and creating your own custom functions, you can greatly extend the capabilities of your SASS stylesheets.