HTML table cell partial background fill

fatdragon picture fatdragon · Jun 9, 2016 · Viewed 8.4k times · Source

I have a table that has a column that shows a % value. To make it more visually appealing, I'd like to display a linear gradient background that corresponds to the % value (e.g. 50% would fill half of the width of the cell).

I figured out how to make gradient background (using ColorZilla's gradient generator) but don't know how to set the width of the background fill....

Current code:

<table border="1" cellpadding="0" cellspacing="0">
    <tr>
        <td width="100" style="background: linear-gradient(to right, rgba(0,150,0,1) 0%,rgba(0,175,0,1) 17%,rgba(0,190,0,1) 33%,rgba(82,210,82,1) 67%,rgba(131,230,131,1) 83%,rgba(180,221,180,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */">50%</td>
    </tr>
</table>

Answer

Harry picture Harry · Jun 9, 2016

It is pretty simple. Just set the background-size value based on percentage like in the below snippet. If the gradient is horizontal then change the size in X-axis to match the percentage value or if gradient is vertical then change the size in Y-axis.

For negative values change the direction of gradient from to right to to left and set 100% 100% as value for background-position to get it right aligned.

(Inline styles are used only because you'd need to set it via JS to match the % value. This cannot be done with CSS.)

td {
  width: 25%;  /* only for demo, not really required */
  background-image: linear-gradient(to right, rgba(0, 150, 0, 1) 0%, rgba(0, 175, 0, 1) 17%, rgba(0, 190, 0, 1) 33%, rgba(82, 210, 82, 1) 67%, rgba(131, 230, 131, 1) 83%, rgba(180, 221, 180, 1) 100%);  /* your gradient */
  background-repeat: no-repeat;  /* don't remove */
}
td.negative {
  background-image: linear-gradient(to left, rgba(0, 150, 0, 1) 0%, rgba(0, 175, 0, 1) 17%, rgba(0, 190, 0, 1) 33%, rgba(82, 210, 82, 1) 67%, rgba(131, 230, 131, 1) 83%, rgba(180, 221, 180, 1) 100%);  /* your gradient */
  background-position: 100% 100%;
}  
/* just for demo */

table {
  table-layout: fixed;
  width: 400px;
}
table, tr, td {
  border: 1px solid;
}
<table>
  <tr>
    <td style='background-size: 90% 100%'>90%</td>
    <td style='background-size: 50% 100%'>50%</td>
    <td style='background-size: 20% 100%'>20%</td>
    <td style='background-size: 100% 100%'>100%</td>
  </tr>
  <tr>
    <td style='background-size: 90% 100%' class='negative'>-90%</td>
    <td style='background-size: 50% 100%' class='negative'>-50%</td>
    <td style='background-size: 20% 100%' class='negative'>-20%</td>
    <td style='background-size: 100% 100%'>100%</td>
  </tr>  
</table>