How to code a responsive circular percentage chart with SVG and CSS.

For a web application I needed to create a percentage circle chart. I chose an implementation with SVG and CSS: flexible, cross browser and quite simple to build. From my perspective the main goal was to have a single parameter to change, with a value from 0 to 100.

Let’s build it!

To do this you have to draw a SVG circle with the circumference equal to 100, and stroke it with single dash line (composed only by one dash and one gap). Set the length of the first dash from 0 to 100, to highlight the section of the circle corresponding to the desired percentage, and use the gap to cover the remaining part.

1. Creation of the SVG circle.

To draw a circle you need the radius and diameter values. Let’s calculate it starting with this simple math formula (something you should have learned at the age of 10 :-) ):

radius = circumference / 2π

So for a circle with a circumference of 100 the value of radius will be:

You have a 36x36 box which contains the 31.831 diameter circle. The box needs to be little bigger than the circle because you have to consider the stroke width. The initial point of the circle path is set at these coordinates inside the box:

x: 18 (36/2)

y: 2.0845 ((36–31.831) / 2)

2. The dash and the gap.

Now you have the circle: to partially stroke it, you must use stroke-dasharray property.

Usage:

stroke-dasharray=”<dash-length>, <gap-length>”

So, you can cover the circumference of 100, setting the <dash-length> value to the desired percentage: