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!

1. Creation of the SVG circle.

radius = circumference / 2π

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

radius = 100 / ( 3,14159 * 2 ) = 15,9155

diameter = 15,9155 * 2 = 31.831

Here is the code for the SVG circle:

<svg viewBox="0 0 36 36">
<path
d="M18 2.0845
a 15.9155 15.9155 0 0 1 0 31.831
a 15.9155 15.9155 0 0 1 0 -31.831"
fill="none"
stroke="#444";
stroke-width="1";
/>
</svg>

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.

Usage:

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

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

stroke-dasharray="100, 100" --> 100%
stroke-dasharray="75, 100" --> 75%
stroke-dasharray="50, 100" --> 50%
stroke-dasharray="25, 100" --> 25%
stroke-dasharray="0, 100" --> 0%
...

The final SVG:

<svg viewBox="0 0 36 36">
<path
d="M18 2.0845
a 15.9155 15.9155 0 0 1 0 31.831
a 15.9155 15.9155 0 0 1 0 -31.831"
fill="none"
stroke="#444";
stroke-width="1";
stroke-dasharray="75, 100"
/>
</svg>

3. Put all together with some CSS styles and animations.

A basic setup:

Open this example in CodePen.

A more comprehensive example:

Open this example in CodePen.

Browser compatibility

  • Firefox 4+
  • Opera 12+
  • Safari 5.1+
  • Internet Explorer / Edge 9+ (*)

(*) Note: The keyframes animation on css3 property “stroke-dasharray” works only on Edge.

Front-end developer and UX/UI designer.

Front-end developer and UX/UI designer.