Skip to content

Instantly share code, notes, and snippets.

@mirisuzanne
Created July 19, 2012 05:42
Show Gist options
  • Save mirisuzanne/3141010 to your computer and use it in GitHub Desktop.
Save mirisuzanne/3141010 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));
}
@jina
Copy link

jina commented Jul 19, 2012

Oh sweet!!! That's awesome. Updating it the moment I get to my desk. Thanks again!!!

@jina
Copy link

jina commented Jul 19, 2012

IT WORKS!!! hugs all around!!!

@jina
Copy link

jina commented Jul 21, 2012

Check out the CodePen.io I made so you can see this in action: http://codepen.io/jina/pen/iosjp

@markuppatterns
Copy link

How to set different width to each color of stripe?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment