Nirnae Nirnae - 3 months ago 9
CSS Question

Override background-color by a certain percentage

I'm adding row throught a

<table>
with a
foreach
.

At some point I want a cell to have a grey background based on the percentage calcultated in PHP.

Ex: 50% means half the background of the cell with be grey the rest will stay blank | 33,33% = 1/3 of the background etc..

The problems I've met is either the text in the
<td>
got streched by any other div, if I apply the color to the
<td>
I'll also override the text later on 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 the style applied so far :

table {
margin-left:auto;
margin-right:auto;
font-size:18px;
}

table, th, td {
text-align: center;
border: 1px solid black;
position:relative;
}


I must be missing something but CSS really isn't my thing, any explanation or help would be greatly appreciated.

Answer

Here is a simple solution using 2 divs with a fixed width. The percentage is inserted directly in the markup. With setting the <p> to an absolute position, you shouldn't have problems with stretching the 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, because it only uses elements width.

Comments