How to Use SCSS Functions

Using SCSS functions allows you to create dynamic and reusable logic for styling values in your stylesheets. You can define a function using @function and return calculated values with @return, making it useful for tasks like color manipulation, spacing calculations, or unit conversions. Functions help reduce repetition and keep your code more organized and efficient. They can be combined with variables and mixins to build powerful styling systems. Overall, SCSS functions improve flexibility and make your styles more maintainable and scalable.

What Are SCSS Functions?

SCSS functions are used to return a value after performing some logic or calculation. Unlike mixins, functions are mainly used for computing values (like colors, sizes, etc.).

Example:

@function double($value) {
@return $value * 2;
}

.box {
width: double(10px); // 20px
}

Creating Custom Functions

You can define your own functions using @function and return values using @return.

Example:

@function spacing($size) {
@return $size * 8px;
}

.container {
padding: spacing(2); // 16px
}

Using Built-in SCSS Functions

SCSS provides many built-in functions for colors, math, strings, and more.

Example (Color Functions):

$primary: #3490dc;

.button {
background: lighten($primary, 10%);
}

.button-hover {
background: darken($primary, 10%);
}

Functions with Conditions

You can use conditional logic inside functions to return different values based on input.

Example:

@function text-color($bg) {
@if (lightness($bg) > 50) {
@return black;
} @else {
@return white;
}
}

.box {
background: #222;
color: text-color(#222);
}

Real-World Usage (Dynamic Design System)

Functions are useful for building scalable design systems, like consistent spacing, font sizes, or color variations.

Example:

@function rem($px) {
@return $px / 16px * 1rem;
}

h1 {
font-size: rem(32px); // 2rem
}

p {
font-size: rem(16px); // 1rem
}