Override background color by a certain percentage

I am adding a line through t <table> with foreach .

At some point, I want the cell to have a gray background based on the percentage calculated in PHP.

Example: 50% means half the background of the cell with gray, the rest will remain empty | 33.33% = 1/3 of the background, etc.

The problems I ran into is either the text in the <td> received by any other div, if I applied the color to the <td> , I also override the text later, etc.

Here is the code:

 $percent = 1/3; // For example $percent_friendly = number_format( $percent * 100, 2 ); //This will return 33.33 echo '<td>'.$percent_friendly.' % <div style="background-color: grey"> // So I want the grey to fill 33.33% of the space </div> <div style="background-color: white"> </div> </td>'; 

and applied style:

 table { margin-left:auto; margin-right:auto; font-size:18px; } table, th, td { text-align: center; border: 1px solid black; position:relative; } 

I need to miss something, but CSS is really not my thing, thanks for the help or help.

+6
source share
3 answers

Here is a simple solution using 2 fixed width divs. The percentage is inserted directly into the markup. When you install <p> in the absolute position you do not have to create problems with stretching td.

 table { border: 1px solid; } td { height: 50px; } .progress { padding:0; width: 200px; border: 1px solid #555; background: #ddd; position: relative; } .bar { height: 100%; background: #57a; } .bar p { position: absolute; text-align: center; width: 100%; margin: 0; line-height: 30px; } 
 <table> <tr> <td class="progress"> <div class="bar" style="width: 33.33%"><p>33.33% complete</p></div> </td> </tr> <tr> <td class="progress"> <div class="bar" style="width: 16.66%"><p>16.66% complete</p></div> </td> </tr> <tr> <td class="progress"> <div class="bar" style="width: 66.66%"><p>66.66% complete</p></div> </td> </tr> </table> 

Should work in all browsers as it uses only the width of the elements.

+4
source

In PHP:

 echo " <td> <div class='progress-bar' style='width: $percent_friendly%'></div> <span>$percent_friendly%</span> </td>"; 

In CSS:

 td { position: relative; } td .progress-bar { position: absolute; background: grey; top: 0; bottom: 0; left: 0; } td span { position: relative; } 

This allows you to apply any styles of structure / font to the td element, and the progress bar is automatically configured independently.

+2
source

You can use a linear gradient for the background color, if you don't mind, it looks a bit confusing:

 echo '<td style="background: linear-gradient(to right, grey 0%,grey '.$percent.'%,white '.$percent.'%,white 100%);">'. $percent_friendly.'%'. '</td>'; 

Remember that this does not work in IE9 and below.

0
source

All Articles