Pie Slices

Recently I found myself in need of an easier way of working with conical gradients. (Take a close look at some of the smaller details on this blog and you might guess why.)

Standard CSS syntax for conic gradients isn’t that complicated:

background: conic-gradient(red, orange, yellow, green, blue)

But that’s just the standard usage. If you want to do something fancier, like have each segment of the gradient have sharp boundaries instead of the default fade, you need to specify the degrees at which one color stops and the next color starts:

conic-gradient( #f00 0deg 72deg, #ff0 72deg 144deg, #0f0 144deg 216deg, #0ff 216deg 288deg, #00f 288deg 360deg, #f0f 360deg, #f00)

And that gets complicated. Any time I need to do a lot of manual calculating, I start thinking about doing that programmatically.

There are other things it would be nice to do automatically, too. Standard conical gradients have a gradient followed by a sharp edge. Maybe you’d rather all the colors faded smoothly into each other, though. That requires adding an extra value at the end. Again, that’s something a mixin could do.

The solution turned out to be interesting, and I learned something about string manipulation in Sass.

The code, explained

Let’s take a look at the code. I find it easier to do the explaining in the code itself, rather than breaking out each line and discussing it in the main post. As a reader, I prefer seeing the line in the context of the code around it (and also, this makes it easier for you to just grab all the code and play with it yourself).

See the Pen no-dec – USE THIS by Chris Silverman (@csilverman) on CodePen.