10/13/2015 - 1:10 PM

Rainbow stripe mixin with SCSS + Compass

Rainbow stripe mixin with SCSS + Compass

Rainbow stripe mixin with SCSS + Compass

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?


  1. [check] Use variables for colors so they can be swapped out for different colors.
  2. [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?
  3. [check] The colors are defined twice for the color starts and stops. Can this be done better?
  4. [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));