In this tutorial I will show you can combine CSS and PHP to represent data as percentage bar. This is very good for showing polls and so on. In order to use this in a real application you must take data from a SQL database, then use it in your php scripts. I am using two images:
- one 300×18:
- second one 600×18:
Okay now let’s start with the code. First the css. We can save it into a file style.css:
background: url(percentimage_back.png) top left no-repeat;
margin: 5px 0 0 0;
background-position: 1px 0;
We will control the the position of the background image based on the input data. To represent the 0 % percentage the position would be -300, and for 100 % would be 0. The code:
<link rel="stylesheet" type="text/css" href="style.css">
$nr1 = 70;
$nr2 = 30;
$total = $nr1 + $nr2;
$proc =($nr1 / $total) * 100;
$p = number_format($proc,1,",",".");
$x= -300 + $proc * 3;
<img src="percentimage.png" alt="<?php echo $p; ?>" class="percentImage" style="background-position: <?php echo $x; ?>px 0pt;" />
<td width="100" align="right" valign="middle">
<?php echo $p."%"; ?>
In $nr1 and $nr2 I am keeping the nr for representing the data.
In $proc I am computing $nr1 as a percentage and then I am formatting the data with one decimal.
After that I am using percentimage.png for displaying the data.
I hope you enjoyed this PHP tutorial in which you’ve seen how to represent data as percentage using PHP, HTML and little bit of css.
Leave a Reply