tezvyn:

Sass Functions: Reusable Logic for Your Styles

AI-drafted, machine-checkedSource: sass-lang.comadvanced

Sass functions are like JavaScript functions for your CSS, letting you compute and return a single value. Use them to centralize complex logic, like generating a color palette. The footgun: don't use functions for side-effects; that's what mixins are for.

WHY IT EXISTS Native CSS lacks a way to define reusable logic for calculating property values. This often leads to repeated formulas or manually calculated values scattered throughout a codebase. Sass functions solve this by providing a way to encapsulate complex operations, making stylesheets more maintainable, readable, and less repetitive (DRY).

THE MENTAL MODEL Think of a Sass function as a pure, reusable calculator for your stylesheet. You give it some inputs (arguments), it performs some calculations, and it hands you back a single, clean result (a value like a color, number, or string). It doesn't paint the wall; it just tells you the exact color code to use.

HOW IT WORKS You define a function with the @function at-rule, giving it a name and an optional list of arguments. Inside the function body, you write SassScript to perform operations. The function must end with an @return at-rule, which specifies the value the function call will resolve to. You then call the function just like a native CSS function, like color: my-function(#fff);. Arguments can be made optional by providing a default value, for example: @function my-func(color, amount: 100%) { ... }.

WHEN TO USE IT Use functions for any complex, repeated calculation that results in a single value. Common use cases include: creating a function to convert pixels to rems, generating a shade or tint of a color, or calculating a value in a modular scale. They are perfect for building the logic behind design token systems.

WHEN NOT TO USE IT Do not use functions to produce side-effects or output blocks of CSS. If you need to generate multiple CSS properties, apply a set of styles directly, or modify a global variable, use a @mixin instead. A function that doesn't @return a value is useless, and one that does more than just return a value is a code smell.

ONE CANONICAL EXAMPLE A function to create an accessible inverted color. It takes a color and an optional amount, calculates the inverse hue, and mixes it with the original color to control the intensity.

@function invert(color, amount: 100%) { inverse: change-color(color, hue: hue(color) + 180); @return mix(inverse, color, $amount); }

// Usage: .header { background-color: invert(#036, 80%); }

This centralizes the color inversion logic, making it reusable and easy to update.

Read the original → sass-lang.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.