css - 相同的背景颜色,不同的渐变宽度
问题描述
我试图在某些td
s 的一部分上获得背景颜色,使其看起来类似于进度条背景:从左侧到中间某处,它是彩色的,在该百分比之后,它是白色的。如果它是 100%,当然,整体td
是彩色的。
颜色 alinear-gradient
在所有td
s 上都相同,但长度会有所不同。我只有 3 个长度:
- 30%
- 70%
- 100%
- 也是 0%,但它只是空的,所以这是不可能的
为此,我为每个变体使用了一个特定的类,.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 颜色,或者我必须像我的第一个示例中那样做吗?
解决方案
您可以依赖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>
推荐阅读
- computational-geometry - 如何在 3D 凸包中找到 x、y 和 Z 的最小值和最大值?
- c++ - 如何在 C++ 类中删除它(使其不进入无限循环)
- ios - iOS 构建时错误 Asset.xcasset No such file or directory
- javascript - 如何将 Chart JS 颜色方案插件导入 Salesforce Lightning 组件?
- movesense - Movesense 的 MAX3000x 提供哪些唤醒触发状态?
- postgresql - postgresql除以零错误处理
- javascript - 如何更改对象数组中的值
- c - 为什么我们在嵌入式系统中的内存有限?
- vert.x - 正文中发送的 OpenID 访问令牌,放在标头中
- excel - 在 PowerBI 中显示表中的原始数据