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

Sergio Pedercini
3 min readMay 17, 2017

--

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:

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.

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:

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

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

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

--

--