Dynamic Repeating Sass Colors
1 min read

I've recently added a new feature to EveryDollar that involved creating a donut chart with an associated colorful legend. The mock-ups had a few colors represented, but I soon wondered what colors should I should used if more items existed.

After talking with the designer, we decided that there would be an initial set of predefined colors (#56c7fa, #f76540, #ffcb05, #62cd9f, #b67baa) that would gradually get darker (#068dcb, #b02907, #846900, #2a855e, #723f68) and then cycle back around if more were needed.

Dynamic Sass Colors

So, I first assigned the initial set of colors to a Sass list ($chartColors) and iterated over them and appended a sligtly darker version of each one to the list. Thanks to built-in Sass directives and functions (for, append, and darken) that didn't prove to be too difficult.

$chartColors: #56c7fa, #f76540, #ffcb05, #62cd9f, #b67baa;
@for $i from 1 through length($chartColors) {
$chartColors: append($chartColors, darken(nth($chartColors, $i), 25));
}
view raw colors.scss hosted with ❤ by GitHub

CSS Repeating Colors

In order to cycle through the final list of colors I used the :nth-of-type pseudo-class in CSS (supported in IE9+ and all other major browser versions). The selector .color:nth-of-type(10n+3) { background-color: #ffcb05; } sets the background color of the 3rd, 13th, 23rd, 33rd, etc... .color elements to #ffcb05.

.color:nth-of-type(10n+1) {
background-color: #56c7fa;
}
.color:nth-of-type(10n+2) {
background-color: #f76540;
}
.color:nth-of-type(10n+3) {
background-color: #ffcb05;
}
/* ... other 10n+# variations ... */
view raw repeated-colors.css hosted with ❤ by GitHub

Resources

Sass Repeating Colors

Using a simple Sass for loop I was able to create the 10 selectors needed to target our dynamically supported colors and enable them to continually cycle (using :nth-of-type) if there are lots of chart elements.

$chartColorsLength: length($chartColors);
.color {
@for $i from 1 through $chartColorsLength {
&:nth-of-type(#{$chartColorsLength}n+#{$i}) {
background-color: nth($chartColors, $i);
}
}
}
view raw repeated-colors.scss hosted with ❤ by GitHub

Demo

Here is a demo of all the pieces working together. You'll notice that the color logic is completely outside the HTML markup (<div class="color"></div>). Sass is doing most of the manual work during the procompilation step and the resulting CSS :nth-of-type pseudo-classes are the magic that takes over during runtime.

See the Pen jEKMbg by Elijah Manor (@elijahmanor) on CodePen.

Edit post on GitHub


JavaScript Code Smells
Custom Searches with Alfred