SCSS by Example: Functions
Computing values with custom and built-in functions through this sample code showing function definition with @function directive, @return statements, built-in color manipulation functions, and function invocation in property values.
Code
// Define a function
@function calculate-width($col-count) {
@return 100% / $col-count;
}
// Using built-in color functions
$base-color: #3498db;
$dark-color: darken($base-color, 10%);
$light-color: lighten($base-color, 20%);
.column-3 {
width: calculate-width(3); // Returns 33.3333%
background-color: $light-color;
border: 1px solid $dark-color;
}
.column-4 {
width: calculate-width(4); // Returns 25%
}Explanation
SCSS functions are defined using the @function directive and must contain a @return statement that specifies the value to be returned. Unlike mixins which output CSS declarations, functions compute and return a single value that can be used in property assignments, variable definitions, or as arguments to other functions. Functions support parameters with optional default values and can perform complex calculations using SCSS operators and control directives.
Sass includes an extensive library of built-in functions organized into categories:
- Color functions like
darken(),lighten(),saturate(),desaturate(),mix(),rgba() - String functions like
quote(),unquote(),str-length(),str-slice() - Number functions like
percentage(),round(),ceil(),floor(),abs() - List functions like
length(),nth(),join(),append() - Map functions like
map-get(),map-merge(),map-keys(),map-values()
Custom functions enable abstraction of complex formulas and calculations into reusable, readable units. The calculate-width example demonstrates a simple mathematical function, but functions can also contain conditional logic using @if, loops using @for or @each, and can call other functions. Functions are evaluated at compile time, with the return value replacing the function call in the final CSS output.
Code Breakdown
@function defines custom function that must return a value.@return statement specifies the computed value to return.darken($base-color, 10%) uses built-in function to reduce lightness by 10%.calculate-width(3) invokes function, return value replaces call in CSS.
