How to Create a Pie Chart Using Only HTML and CSS
Build a simple Pie Chart with HTML and CSS
In this post, I will show you how to create a pie chart using HTML and CSS.
You can create a Pie Chart in HTML using a simple CSS function called conic-gradient
.
First, we add an element to our HTML page, which acts as a placeholder for our pie chart.
We need to provide a width and a height to the element, which determine the size of our pie chart:
.piechart {
width: 400px;
height: 400px;
}
Then, we need to make our pie chart circle-shaped by setting the border-radius value to 50%:
.piechart {
border-radius: 50%;
}
And finally we are ready to populate the pie chart with our data.
Assets | Color | Quantity |
Laptop | #FFBA1C | 2500 (50%) |
Desktop | #4BD985 | 1000 (20%) |
CCTV | #B827FF | 1500 (30%) |
To apply these values to our pie chart, we need to partition it into 3 sections, a section for each asset. To create the sections, we can use the conic-gradient CSS function. Each section has a color, a start position and a stop position.
For example, Laptop is represented by the Yellow (#FFBA1C) color and has 50% of the total asset. Therefore, we want a Yellow section from 0% to 50%.
Then, we want to plot a Green (#4BD985) section representing the Desktop, which has 20% of the total asset. This results in a green section going from 50% to 70%.
Similarly, to represent the CCTV we want a Purple (#B827FF) section going from 70% to 100%.
.piechart {
background-image: conic-gradient( #FFBA1C 0% 50%, #4BD985 50% 70%, #B827FF 70% 100%);
}
If you want to control pie chart value dynamically, use inline value:
Comments
Leave a Comment