我们可以参数化CSS样式吗?

时间:2016-03-15 15:17:44

标签: css parameters

由于这个CSS代码,我正在显示一个干净的百分比背景:

.percent {
   background: linear-gradient(to left,  #FFBFBF 10%, #9BF7BF 10%) no-repeat;
   background-position-y: 45%;
   background-size: 100% 21px;
}

我的问题是:我能否以某种方式对HTML中的百分比(此处为10%)进行参数化?理想情况下它可能看起来像<td class="percent(10)">

我能想到的唯一解决方案是生成100个.percent CSS样式,并从<td class="percent10"><td class="percent87">中调用HTML中的正确样式,但这非常难看,不是&#39;是吗?

现在渲染看起来像这样:

CSS Percentage

2 个答案:

答案 0 :(得分:0)

如何在概念上接近这个的简单方法:

<div style="position: relative; background: #FFBFBF; width: 200px; height: 25px;">
    <div style="position: absolute; top: 0; left: 0; background: #9BF7BF; width: 87%; height: 100%;"></div>
    <div style="position: absolute; top: 0; left: 0;">87%</div>
</div>

&#34;背景&#34; div(最外面的一个)有粉红色;最重要的是你放了一个绿色的div width你变化了,最重要的是你把你的百分比写成文字。

答案 1 :(得分:0)

最后,我实现了丑陋的解决方案。然而,考虑到单元格的数量可能非常大,我认为我们不能在HTML和CSS文档中的字符数方面做得更好。

/* Generates somehow these 101 lines */
.pct0 { background: linear-gradient(to right, #9BF7BF 0%, #FFBFBF 0%); } 
.pct1 { background: linear-gradient(to right, #9BF7BF 1%, #FFBFBF 1%); } 
(...)
.pct100 { background: linear-gradient(to right, #9BF7BF 100%, #FFBFBF 100%); } 

/* This don't work if rules below comes before the rules above */
.pct0,.pct1, (...) , pct100
{ 
  background-position: center;
  background-size: 95% 18px;
  text-align: right;
  background-repeat: no-repeat;
}

HTML使用样式<td class="pct0"> <td class="pct1">,... <td class="pct100">

CSS percentage display