Writing Custom Functions
Sass functions encapsulate calculations and return values using @return. They are suitable for calculations that should be reused in multiple declarations or components.
A function should have a clear contract: its arguments represent inputs, and its returned value represents the result. Keep functions focused and avoid using them when a direct CSS value is easier to understand.
Sass functions execute during compilation. They cannot inspect the browser viewport, query the DOM, or retrieve a runtime CSS custom property's computed value.
For browser-dependent calculations, emit a CSS calculation expression rather than trying to evaluate browser state during Sass compilation.
@function spacing($step, $base: 0.25rem) {
@return $step * $base;
}
.card {
padding: spacing(4);
gap: spacing(2);
}
.section {
margin-block: spacing(8);
}spacing(4) produces 1rem, while spacing(2) produces 0.5rem.
A spacing function can help enforce a consistent design scale. In a larger design system, you may also validate inputs or use a map to restrict values to an approved token set.Which directive returns a calculated value from a Sass function?