Create pie charts and donut charts in CSS
Looking at graphs and charts in web apps, I always thought it would be complex to make those. But do you know how easy it is to make pie charts and donut charts like these in CSS?
Linear gradients and radial gradients are quite common, but very recently I came across Conic Gradients. With this, you can create a gradient with color transitions rotated around a center point.
Here's the simplest example of a circle with conic gradient:
This is what you get:
As you can see, there's a gradual transition from pink
to purple
, clockwise. With conic-gradient
, you can use color stops to add different colors at exact angles using degrees
. And hence you can specify at what degree each color starts and ends.
This says, we want the color pink
from 0 degrees to 190 degrees, yellow
from 190 degrees to 260 degrees and blue
from 260 degrees to 360 degrees. There we have a pie chart!
Next, to create a donut chart, we only have to make a hole in this pie chart. We can use the ::after
pseudo element to create a circle of the same background color and place it at the center of the pie chart.
This gives us our donut chart.
Here's the working demo of the pie chart and donut chart.
Hope you enjoyed reading this :)
📘 Complete Guide to CSS Flex and Grid
If you loved this write-up and how it was explained, you’ll absolutely love my eBook CSS Flex and Grid. Check it out!
📨 Newsletter suggestion
I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇
Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.