Dynamic Repeating Sass Colors

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.

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.


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.


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.