Welcome to a tutorial on how to create a simple pie chart using pure HTML and CSS. Need to display a pie chart in your project? But don’t want to introduce loading bloat with third-party libraries? Here’s a really simple version – Read on! Show ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TABLE OF CONTENTS
DOWNLOAD & DEMOFirstly, here is the download link to the example code as promised.
QUICK NOTESIf you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
EXAMPLE CODE DOWNLOADClick here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
PIE CHART DEMOFirst Second Third
PURE CSS PIE CHARTAll right, let us now get into the steps of building a simple pie chart using HTML and CSS only.
PART 1) PIE CHART1A) THE HTMLpie-chart.html
Yes, a 1B) THE CSSpie-chart.css
PART B) THE LEGEND2A) THE HTMLpie-chart.html
Now, a few tutorials on the Internet do “brute force calculations” to put the labels/legend into the pie chart itself. I figured that is “not simple”, and the easiest way is to just create a separate legend.
2B) THE CSSpie-chart.css
Not much of a mystery here either – The legend is just a “grid table”. The first cell is the “color block”, followed by the name of the segment itself.
USEFUL BITS & LINKSThat’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
IT WORKS, BUT NOT FOR COMPLEX PIES.This simple pie chart works great if you only have a few segments, but it quickly grows painful when there are a lot of segments to deal with. Manually calculating the segments, assigning the colors, updating the legend is not fun to deal with… So a bit of Javascript to “automate” the calculation will be great – I shall leave that as a possible future update.
COMPATIBILITY CHECKS
CSS grid and conic gradient are well-supported on all modern “Grade A” browsers.
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEETThank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding! |