HTML table 单元格部分背景填充

HTML table cell partial background fill

我有一个 table,其中有一列显示 % 值。为了使其更具视觉吸引力,我想显示与 % 值相对应的线性渐变背景(例如,50% 将填充单元格宽度的一半)。

我想出了如何制作渐变背景(使用 ColorZilla 的渐变生成器)但不知道如何设置背景填充的宽度....

当前代码:

<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>

这很简单。只需根据以下代码段中的百分比设置 background-size 值。如果渐变是水平的,则更改 X 轴的大小以匹配百分比值,或者如果渐变是垂直的,则更改 Y 轴的大小。

对于负值,将渐变方向从 to right 更改为 to left 并将 100% 100% 设置为 background-position 的值以使其右对齐。

(使用内联样式只是因为你需要通过 JS 设置它来匹配 % 值。这不能用 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>