背景颜色相同,渐变宽度不同

时间:2018-12-05 14:19:54

标签: css css3 linear-gradients

我正试图在某些td的一部分上获得背景色,以使其看起来类似于进度条背景: 从左到中间的某个地方是彩色的,然后是该百分比的白色。 当然,如果是100%,则整个td都是彩色的。

颜色linear-gradient在所有td上都相同,但长度会有所不同。我只有3种长度:

  • 30%
  • 70%
  • 100%
  • 也为0%,但那时它只是空的,所以这是不可能的

为此,我为每个变体.progress_**使用了一个特定的类。 每个类的linear-gradient属性都有两个background。 这是我目前正在使用的CSS:

.progress_30 {
    background:
        linear-gradient(to right,
            rgba(0, 0, 0, 0) 0%,
            rgba(255, 255, 255, 0) 30%,
            rgba(255, 255, 255, 1) 30%
        ),
        linear-gradient(to right, yellow, green)
    ;   
}
.progress_70 {
    background:
        linear-gradient(to right,
            rgba(0, 0, 0, 0) 0%,
            rgba(255, 255, 255, 0) 70%,
            rgba(255, 255, 255, 1) 70%
        ),
        linear-gradient(to right, yellow, green)
    ;   
}
.progress_100 {
    background:
        linear-gradient(to right,
            rgba(0, 0, 0, 0) 0%,
            rgba(255, 255, 255, 0) 100%,
            rgba(255, 255, 255, 1) 100%
        ),
        linear-gradient(to right, yellow, green)
    ;   
}

如您所见,有很多重复的地方。 我至少要将颜色放在单独的.progress类中,以便可以轻松更改颜色而无需更改长度,因此将来可以增加或更改某些长度而无需更改颜色。

所以我尝试了这个:

.progress {
    background: linear-gradient(to right, yellow, green);
}
.progress_30 {
    background:
        linear-gradient(to right,
            rgba(0, 0, 0, 0) 0%,
            rgba(255, 255, 255, 0) 30%,
            rgba(255, 255, 255, 1) 30%
        )
    ;
}
.progress_70 {
    background:
        linear-gradient(to right,
            rgba(0, 0, 0, 0) 0%,
            rgba(255, 255, 255, 0) 70%,
            rgba(255, 255, 255, 1) 70%
        )
    ;
}
.progress_100 {
    background:
        linear-gradient(to right,
            rgba(0, 0, 0, 0) 0%,
            rgba(255, 255, 255, 0) 100%,
            rgba(255, 255, 255, 1) 100%
        )
    ;
}

这不能完全起作用:右侧的白色部分是正确的长度。但是在左侧,我看不到linear-gradient,只有页面的背景色(不是白色)。

有没有办法在CSS中获得尽可能少的重复,至少linear-gradient的颜色仅设置一次,还是必须像第一个示例中那样?

1 个答案:

答案 0 :(得分:2)

您可以依靠background-size并将渐变声明保留在同一类中:

div {
  min-height: 50px;
}

.progress {
  background: 
   linear-gradient(#fff, #fff) right no-repeat, 
   linear-gradient(to right, yellow, green);
}

.progress_30 {
  background-size: 70% 100%, auto;
}

.progress_70 {
  background-size: 30% 100%, auto;
}

.progress_100 {
  background-size: 0% 100%, auto;
}
<div class="progress progress_30"></div>
<div class="progress progress_70"></div>
<div class="progress progress_100"></div>

如果您想考虑更多的百分比值,可以使用CSS变量简化更多操作:

div {
  min-height: 50px;
}

.progress {
  background: 
   linear-gradient(#fff, #fff) right/calc(100% - var(--p,50%)) 100% no-repeat, 
   linear-gradient(to right, yellow, green);
}
<div class="progress" style="--p:30%"></div>
<div class="progress" style="--p:68%"></div>
<div class="progress" style="--p:80%"></div>

<div class="progress" ></div>

相关问题