site logo

Simple bar graph with help of CSS

This way of graph drawing originates in design of gauging report. I needed to save report into single one .html file without any additional .gif files. Then it was easy to send such .html file as an e-mail attachement. The graph is used for drawing of measured values distribution, so called histogram (frequency diagram).

 
 
 
 
 
 
 
 
 
 
 
 

In the left side you can see sample of modified graph from forenamed report. Bar drawing is done with help of CSS parameter border-left. Server adds calculated value of border  width to the inline style (red part of code). In case of empty interval, light grey 1 pixel bar is displayed as a mark of interval where no value was measured. Further follows html code sample. I would like to point to hard space ( ), without that, empty div would not be rendered. Because of that hard space, we have to set small enough font (to be less than height of div element). The group of graph elements are wrapped to the ouside div.

...
<style type="text/css">
.gr {font: 4px Arial; height: 8px; width: 100%; margin-bottom: 1px;}
</style>
</head>

<body>
...
<div style="width: 32px; float: left;">
...
<div class="gr" style="border-left: 1px solid #ccc;">&nbsp;</div>
<div class="gr" style="border-left: 8px solid #666;">&nbsp;</div>
<div class="gr" style="border-left:12px solid #666;">&nbsp;</div>
...
</div>

</body>
</html>

spring 40%
summer 30%
autumn 10%
winter 20%
Similar graph could be used e.g. for graphic output of public inquiry results. Let's try to complete graph with text data. Left aligned text causes that it works the same way in IE, FF and Opera, but the result is not very nice. I did not find a simple way how to align graph to left and text to right with help of single outside div element.

 
spring 40%
 
summer 30%
 
autumn 10%
 
winter 20%

Let's try to create graph with the help of so much refused tables. To the first column we put bar graph, to the second column we write text. Now we can align text to the left, or to the right. Finally IE, FF and Opera reneders graph and text identicaly. Code sample follows.

...
<style type="text/css">
.gr2 {font: 12px/16px Arial; margin-bottom: 1px;}
.tx2 {font: 12px/16px Arial; text-align: right; padding-right: 4px;}
</style>
</head>

<body>
...
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
<div class="gr2" style="border-left: 40px solid #6f0;">&nbsp;</div>
</td>
<td class="tx2">spring 40%</td>
</tr>
...
</table>

</body>
</html>

Drawing graph with the help of CSS border-width fits in cases when we do not want, or we can not use img elements. It is not convenient for more complex graphing, where we may get into problem with proportions of div element.

updated 2023-10-31