按一定百分比覆盖背景颜色

Nir*_*nae 6 html css php background percentage

我加入行throught一个<table>foreach.

在某些时候,我希望一个单元格具有基于PHP中计算的百分比的灰色背景.

例如:50%意味着细胞背景的一半是灰色的,其余的将保持空白 33,33%= 1/3的背景等.

我遇到的问题是<td>被任何其他div拉伸的文本,如果我将颜色应用于<td>我将稍后覆盖文本等.

这是代码:

$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>';
Run Code Online (Sandbox Code Playgroud)

和迄今为止应用的样式:

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

table, th, td {
    text-align: center;
    border: 1px solid black;
    position:relative;
}
Run Code Online (Sandbox Code Playgroud)

我必须遗漏一些东西,但CSS真的不是我的东西,任何解释或帮助将不胜感激.

and*_*eas 4

这是一个使用 2 个固定宽度的 div 的简单解决方案。百分比直接插入标记中。将 设定<p>为绝对位置后,拉伸 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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

应该适用于所有浏览器,因为它只使用元素宽度。

  • 只需将进度类移至“td”并删除现在无用的“div” (2认同)