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.
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:
-
<ul>
-
<li><span>400</span></li>
-
<li><span>20</span></li>
-
<li><span>30</span></li>
-
<li><span>233</span></li>
-
</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
-
$values = ’400,20,30,233,312,78,20,67′;
-
$height = 100;
-
$width = 600;
-
$bargap = 0;
-
include(‘csscharts.php’);
-
?>
Of course, this can also be turned into a web service – you can get the chart with the following URL:
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
-
csscharts(
-
{
-
chart:“<ul class=”barchart” [… the rest of the html …]</ul>”
-
}
-
)
That way you can use it in JavaScript:
-
<script>
-
function csscharts(o){
-
var container = document.getElementById(‘container’);
-
c.innerHTML = o.chart + c.innerHTML;
-
}
-
</script>
-
<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

