loader

Functions in SCSS

What are SCSS Functions?

Functions in SCSS allow you to calculate and return values that can then be used in your styles. Unlike mixins which generate CSS rules, functions return a single value that can be used in a CSS property.

Basic Syntax


@function function-name($parameter1, $parameter2, ...) {
  // Calculations and logic
  @return $result;
}

// Using the function
.element {
  property: function-name(argument1, argument2);
}
                        

Built-in SCSS Functions

SCSS offers many built-in functions that you can use directly. Here are some of the most important categories:

Color Functions


// Lighten color
$light-blue: lighten(#3498db, 20%);  // Makes the color lighter

// Darken color
$dark-blue: darken(#3498db, 20%);    // Makes the color darker

// Adjust saturation
$saturated: saturate(#3498db, 30%);  // Increases saturation
$desaturated: desaturate(#3498db, 30%);  // Decreases saturation

// Add transparency
$transparent-blue: rgba(#3498db, 0.5);  // Adds alpha transparency

// Complementary color
$complement: complement(#3498db);  // Returns the complementary color

// Mix colors
$mixed: mix(#3498db, #e74c3c, 50%);  // Mixes two colors
                        

Mathematical Functions


// Rounding
$rounded: round(3.7);  // 4
$floor: floor(3.7);    // 3
$ceil: ceil(3.2);      // 4

// Min/Max
$min-value: min(5, 10, 3);  // 3
$max-value: max(5, 10, 3);  // 10

// Absolute value
$absolute: abs(-15);  // 15

// Random number
$random: random();  // Random number between 0 and 1
$random-in-range: random(10);  // Random number between 1 and 10
                        

String Functions


// String length
$length: str-length("Hello");  // 5

// Substring
$substring: str-slice("Hello World", 1, 5);  // "Hello"

// Concatenate strings
$combined: "Hello" + " " + "World";  // "Hello World"

// Replace string
$replaced: str-replace("Hello World", "World", "SCSS");  // "Hello SCSS"
                        

List Functions


// List length
$list: 1px, 2px, 3px;
$list-length: length($list);  // 3

// Find element in list
$index: index($list, 2px);  // 2

// Get element from list
$nth-item: nth($list, 2);  // 2px