Pure CSS bar charts as a simple API

I am right now working on a high-traffic project that will run in a sandbox that doesn’t allow me to pull third party JavaScript or use canvas/Flash. Yet I need to generate bar charts from a set of data.

Pure CSS bar charts

The solution to me was to create the charts from HTML using CSS. There have been some solutions for this problem already but I wanted something very simple and easy to maintain. Hence all the markup I am using is this:

XML:

  1. <ul>
  2.   <li><span>400</span></li>
  3.   <li><span>20</span></li>
  4.   <li><span>30</span></li>
  5.   <li><span>233</span></li>
  6. </ul>

Instead of hard-coding any of the trickery necessary I wrote a PHP script to generate the HTML, the styles and do all the math. So all that is needed to render one of the charts is the following code:

PHP:

  1. <?php
  2.   $values = ’400,20,30,233,312,78,20,67′;
  3.   $height = 100;
  4.   $width = 600;
  5.   $bargap = 0;
  6.   include(‘csscharts.php’);
  7. ?>

Of course, this can also be turned into a web service – you can get the chart with the following URL:

http://icant.co.uk/csscharts/csscharts.php?values=400,20,30,233,312,78,20,67&height=100&width=600&bargap=0

And if you specify JSON as the format you get it with a callback to a function called csscharts:

http://icant.co.uk/csscharts/csscharts.php?values=400,20,30,233,312,78,20,67&format=json

JAVASCRIPT:

  1. csscharts(
  2.   {
  3.     chart:“<ul class=barchart [… the rest of the html …]</ul>”
  4.   }
  5. )

That way you can use it in JavaScript:

JAVASCRIPT:

  1. <script>
  2. function csscharts(o){
  3.   var container = document.getElementById(‘container’);
  4.   c.innerHTML = o.chart + c.innerHTML;
  5. }
  6. </script>
  7. <script src=“http://icant.co.uk/csscharts/csscharts.php?values=400,20,30,233,312,78,20,67&format=json”></script>

You can see some demos here, get detailed info about the CSS trickery used and of course download the code on GitHub.

Pure CSS bar charts as a simple API