gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:21:17 24 4
gpt4 key购买 nike

我正在尝试为某些 td 的一部分设置背景色,使其看起来类似于进度条背景:从左边到中间的某个地方,它是彩色的,在那个百分比之后,它是白色的。如果它是 100%,当然,整个 td 都是彩色的。

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

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

为此,我为每个变体使用了一个特定的类,.progress_**。每个类在 background 属性上都有两个 linear-gradient。这是我当前工作的 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 的颜色设置一次,或者我必须像第一次那样做例子?

最佳答案

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

关于css - 相同的背景颜色,不同的渐变宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53634392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com