如何为 "days left?" 创建仅 CSS 的进度条

How to create a CSS only progress bar for "days left?"

我正在尝试做一些或多或少与此类似的事情。

下面是我最好的尝试,但我对结果不满意,因为低值的颜色渐变有太多红色。

.progress {
  height: 5px;
}

.progress-bar {
  background: -webkit-linear-gradient(left, green 0%, red 100%);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<div class="labels">
  <span>20 days left (30 days Trial)</span>
</div>
<div class="progress">
  <div class="progress-bar" role="progressbar" style="width: 33%;"></div>
</div>

演示:https://codepen.io/Ansko/pen/rNBKjRd

这是另一个使用梯度和 CSS 变量的想法:

.progress {
  width:200px;
  height:10px;
  margin:5px;
  background:
    linear-gradient(var(--c,red),var(--c,red)) right/var(--p,50%) 100% no-repeat,
    #ccc;
}
<div class="progress" style="--c:green;--p:80%"></div>
<div class="progress"></div>
<div class="progress" style="--c:yellow;--p:20%"></div>

另一个如果你想自动处理颜色。诀窍是有一个非常大的垂直渐变,你可以根据值滑动以显示不同的颜色。

.progress {
  width:200px;
  height:10px;
  margin:5px;
  background:
    linear-gradient(lightgreen,yellow,red) right 0 bottom var(--p,50%)/var(--p,50%) 600% no-repeat,
    #ccc;
}
<div class="progress" style="--p:95%"></div>
<div class="progress" style="--p:80%"></div>
<div class="progress"></div>
<div class="progress" style="--p:20%"></div>
<div class="progress" style="--p:5%"></div>

这里有一个悬停动画,以便更好地查看:

.progress {
  width:200px;
  height:10px;
  margin:5px;
  background:
    linear-gradient(lightgreen,yellow,red) right 0 bottom var(--p)/var(--p) 600% no-repeat,
    #ccc;
  --p:0%;
  transition:1s;
}
.progress:hover {
  --p:100%;
}
<div class="progress" ></div>


如果你想为范围定义纯色,一个更棘手的代码:

.progress {
  width:200px;
  height:10px;
  margin:5px;
  background:
    /*Red from 0 to 19%*/
    linear-gradient(red,red)       right /var(--p) calc(20%  - var(--p)),
    /*orange from 20% to 49%*/
    linear-gradient(orange,orange) right /var(--p) calc(50%  - var(--p)),
    /*yellow from 50% to 79%*/
    linear-gradient(yellow,yellow) right /var(--p) calc(80%  - var(--p)),
    /*green from 80% to 100%*/
    linear-gradient(green,green)   right /var(--p) 100%,
    #ccc;
  background-repeat:repeat-y;
}
<div class="progress" style="--p:100%"></div>
<div class="progress" style="--p:80%"></div>
<div class="progress" style="--p:79%"></div>
<div class="progress" style="--p:50%"></div>
<div class="progress" style="--p:49%"></div>
<div class="progress" style="--p:20%"></div>
<div class="progress" style="--p:19%"></div>
<div class="progress" style="--p:5%"></div>