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

3

46

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.

Remonstrate answered 6/7, 2015 at 7:18 Comment(1)
I have written an article on the similar lines which might help someone who is looking for depth knowledge stackcoder.in/posts/…Remonstrate
B
66

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% ));
}
Baldheaded answered 6/7, 2015 at 7:54 Comment(2)
Also, you would use functions to access certain data structures in SASS. So for example, map-get-keys is a function because all it does is return the appropriate keys in a SASS map.Baldheaded
This doesn't really answer the question. You can use function in place of every mixing - you just need to return the block of css code with all the rules. The question is when to do it and when you should not do it.Lammas
K
2

@function is useful when you want to reuse it on different CSS properties.

Example, You have dynamic values that you want to use on both height and min-height, then using @function is the one you would use:

@function dynamic-height($height, $padding) {
  @return $height + $padding;
}

.foo {
  min-height: dynamic-height(300px, 30px);
}

.bar {
  height: dynamic-height(300px, 30px);
}

But if you want to reuse it with same CSS properties, then you would use a @mixin:

@mixin dynamic-height($height, $padding) {
  min-height: $height;
  padding: $padding;
}

.foo {
  @include @dynamic-height(300px, 30px);
}
Kure answered 17/1, 2022 at 16:38 Comment(0)
S
1

think of @mixin as it is just a @function that returns a block of style rules.

also, you can use placeholders (like %selector) and @extend

Sunbonnet answered 19/7, 2022 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.