首页 > 解决方案 > 相同的背景颜色,不同的渐变宽度

问题描述

我试图在某些tds 的一部分上获得背景颜色,使其看起来类似于进度条背景:从左侧到中间某处,它是彩色的,在该百分比之后,它是白色的。如果它是 100%,当然,整体td是彩色的。

颜色 alinear-gradient在所有tds 上都相同,但长度会有所不同。我只有 3 个长度:

为此,我为每个变体使用了一个特定的类,.progress_**. 每个类linear-gradient的属性都有两个 s 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只设置一次 's 颜色,或者我必须像我的第一个示例中那样做吗?

标签: csslinear-gradients

解决方案


您可以依赖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>


推荐阅读