Functions and mixins help you reuse code in Sass. Functions return values, while mixins add styles.
0
0
Functions vs mixins comparison in SASS
Introduction
When you want to calculate a value like a color or size.
When you want to add a group of CSS rules multiple times.
When you need to keep your styles organized and avoid repeating code.
When you want to create reusable style blocks with parameters.
When you want to perform simple logic and return a result.
Syntax
SASS
@function function-name($params) { @return value; } @mixin mixin-name($params) { property: value; // more styles }
Functions must return a value using @return.
Mixins insert CSS rules directly where they are included using @include.
Examples
This function doubles a number. The mixin adds a box shadow style.
SASS
@function double($number) { @return $number * 2; } @mixin box-shadow($x, $y, $blur, $color) { box-shadow: $x $y $blur $color; }
Use the function to set width and the mixin to add shadow styles.
SASS
$width: double(10px); .container { width: $width; @include box-shadow(2px, 2px, 5px, rgba(0,0,0,0.3)); }
Sample Program
This Sass code defines a function to convert pixels to rem units. The mixin creates button styles using that function. The button class uses the mixin and function to style a button with consistent spacing and font size.
SASS
@function calculate-rem($px) { @return $px / 16 * 1rem; } @mixin button-style($bg-color, $text-color) { background-color: $bg-color; color: $text-color; padding: calculate-rem(12px) calculate-rem(20px); border: none; border-radius: calculate-rem(4px); cursor: pointer; } .button { @include button-style(#3498db, #fff); font-size: calculate-rem(16px); }
OutputSuccess
Important Notes
Functions only return values and cannot output CSS rules directly.
Mixins can include other mixins and functions for flexible styling.
Use functions for calculations and mixins for reusable style blocks.
Summary
Functions return values like numbers, colors, or strings.
Mixins add CSS rules where included.
Use both to write cleaner, reusable Sass code.