Skip to main
Article

Sass Striped Backgrounds

Jina asked twitter for Sass advice the other day. She was working on a bit of code to create a rainbow-striped background gradient using any set of arbitrary colors. This is my solution, in the form of a Sass function. This requires Sass 3.2 in order to run.

Start by setting a variable to the colors you want:

$rainbow: red orange yellow green blue indigo violet;

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.

Here’s the 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 stripes($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);
}

And how to use it:

.rainbow {
  @include background-image(stripes(left, $rainbow));
}

Jina has posted a demo and explanation on CodePen.

(The real lesson here is that all the colors of the rainbow are acceptable CSS color keywords. Go forth and queer the web.)

Recent Articles

  1. A dog zooming by the camera, up-close, body twisted and eyes wide as it circles a grass yard
    Article post type

    Zoom, zoom, and zoom

    The three types of browser (and CSS!) magnification

    I’m working on an article about fluid typography, and relative units. But instead, I fell down this rabbit hole – or a cleverly-disguised trap? – trying to understand ‘zoom’ in the browser (not Zoom™️ the software). Since I couldn’t find any up-to-date articles on the subject, I thought I shoul…

    see all Article posts
  2. A rusty anchor hanging with the sea in the background.
    Article post type

    Updates to the Anchor Position Polyfill

    Catching up to the spec

    Our sponsors are supporting the continued development of the CSS Anchor Positioning Polyfill. Here’s a summary of the latest updates.

    see all Article posts
  3. A back hoe on the bank of the Suez, trying to free the Ever Given cargo ship
    Article post type

    Learn Grid Now, Container Queries Can Wait

    Take your time with new CSS, but don’t sleep on the essentials

    Several people have asked recently why container queries aren’t being used more broadly in production. But I think we underestimate the level of legacy browser support that most companies require to re-write a code-base.

    see all Article posts