I have the following SASS mixin:
@mixin gradient($start, $end, $fallback: $end, $direction: bottom) {
@if $direction == top {
$directionOld: bottom;
} @else if $direction == right {
$directionOld: left;
} @elseif $direction == bottom {
$directionOld: top;
} @elseif $direction == left {
$directionOld: right;
}
background: $fallback;
background: -webkit-linear-gradient($directionOld, $start, $end);
background: linear-gradient(to $direction, $start, $end);
}
This mixin throws an error because $directionOld is not defined. I can fix it adding this variable by default to the mixin params:
@mixin gradient($start, $end, $fallback: $end, $direction: bottom, $directionOld: top) {
@if $direction == top {
$directionOld: bottom;
} @else if $direction == right {
$directionOld: left;
} @elseif $direction == bottom {
$directionOld: top;
} @elseif $direction == left {
$directionOld: right;
}
background: $fallback;
background: -webkit-linear-gradient($directionOld, $start, $end);
background: linear-gradient(to $direction, $start, $end);
}
But this is not as clean as I want, is there any error in the first code?
Thank you so much!
Mixin do some kind of styling which can be used again again in your whole styling and same you can use variable as much as you can. Functions and Mixins are different. One returns value while the other is used like a macro to substitute.
@mixin is used to group css code that has to be reused a no of times. Whereas the @extend is used in SASS to inherit(share) the properties from another css selector. @extend is most useful when the elements are almost same or identical.
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. Which provides us with the actual code.
Yes you can define new variable in Mixin but you have to define it before use it in an if statement.
I write your code again:
@mixin gradient($start, $end, $fallback: $end, $direction: bottom) {
$directionOld:top !default;
@if $direction == top {
$directionOld: bottom;
} @else if $direction == right {
$directionOld: left;
} @elseif $direction == bottom {
$directionOld: top;
} @elseif $direction == left {
$directionOld: right;
}
background: $fallback;
background: -webkit-linear-gradient($directionOld, $start, $end);
background: linear-gradient(to $direction, $start, $end);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With