Skip to content

Instantly share code, notes, and snippets.

@Kcko
Forked from mirisuzanne/pop-stripe.md
Created October 13, 2015 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kcko/50c9e2fd894ea08e1cfe to your computer and use it in GitHub Desktop.
Save Kcko/50c9e2fd894ea08e1cfe to your computer and use it in GitHub Desktop.
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?

Goals:

  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?

Variables:

// 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;

Function:

// 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);
}

Application:

.rainbow { 
  @include background-image(rainbow(left, $colors));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment