I'm trying to make a horizontal rainbow stripe background gradient mixin, but I feel like this is way too verbose. How can it be better?
Goals:
- [check] Use variables for colors so they can be swapped out for different colors.
- [check] The widths are hard coded for 8 colors. Can it be done smarter where it adjusts to the number of colors you add? Or is that asking too much?
- [check] The colors are defined twice for the color starts and stops. Can this be done better?
- [see below] Right now I define the colors as variables at the top level, then pass them in the mixin. Should they instead be created inside the mixin and then colors are brought in as arguments? Or does that matter?
// You could set individual variables for each color as well.
// You would still pass them all as a single argument,
// or join them into a single variable before passing, as you see fit.
$mycolors: red orange yellow green blue indigo violet;
// Returns a striped gradient for use anywhere gradients are accepted.
// - $position: the starting position or angle of the gradient.
// - $colors: a list of all the colors to be used.
@function rainbow($position, $colors) {
$colors: if(type-of($colors) != 'list', compact($colors), $colors);
$gradient: compact();
$width: 100% / length($colors);
@for $i from 1 through length($colors) {
$pop: nth($colors,$i);
$new: $pop ($width * ($i - 1)), $pop ($width * $i);
$gradient: join($gradient, $new, comma);
}
@return linear-gradient($position, $gradient);
}
.rainbow {
@include background-image(rainbow(left, $colors));
}
Wow, so there is a type-of function. How did i not see this in the documentation? @_@
It seems that there is a bunch of sass functions that i completely missed. compact() is new to me and i was always looking for typeof over type-of. Going back to SASS documentation now :D