@function v/s @mixin in Sass-lang. Which one to use?

After searching a lot in difference between @function and @mixin I ended up here.

Is there any advantage of using @mixin over @funcion or vice versa. In what context they'll be different, how to use them interchangeably, please come up with examples.


Solution 1:

Functions are useful specifically because they return values. Mixins are nothing like functions--they usually just provide valuable blocks of code.

Usually, there are cases where you might have to use both.

For example, if I wanted to create a long-shadow with SASS, I would call a function like so:

@function makelongshadow($color) {
  $val: 0px 0px $color;
  @for $i from 1 through 200 {
    $val: #{$val}, #{$i}px #{$i}px #{$color};
  }
  @return $val;
}

Which would then be called with this mixin:

@mixin longshadow($color) {
  text-shadow: makelongshadow($color);
}

Which provides us with the actual code.

That gets included in the element:

h1 {
    @include longshadow(darken($color, 5% ));
}