CSS variables and opacity

让人想犯罪 __ 提交于 2019-12-30 10:35:32

问题


A quick question to which the answer is probably "NO", but I'm new to CSS variables so I'm not sure.

If I want to define color and later be able to add alpha channel to it, is my only option with CSS variables would be to define it as 3 numbers for RGB channels:

--color: 12 12 12

And later use it ALWAYS with rgb or rgba?

color: rgb(var(--color));

background: rgba(var(--color), .5);

There is really no way to define an actual color and later add alpha to it using only CSS variables? Probably my best bet would be to define 2 vars:

--color-rgb and --color: rgb(var(--color-rgb))


回答1:


You are almost good, you simply need to pay attention to the syntax:

:root {
  --c:255,0 ,0;
  --o:0.5;
}
html {
  background:rgba(var(--c),var(--o));
}
body {
   background:rgb(var(--c));
   height:100px;
}
.box {
 --c:12,12,12;
 --o:0.7;
 background:rgba(var(--c),var(--o));
 color:#fff;
}
<div class="box">
  some content
</div>

You can also define each channel alone:

:root {
  --r:255;
  --g:0;
  --b:0;
  --c:var(--r),var(--g) ,var(--b);
  --o:0.5;
}
html {
  background:rgba(var(--c),var(--o));
}
body {
   background:rgb(var(--c));
   height:100px;
}
.box {
 --c:12,12,12;
 --o:0.7;
 background:rgba(var(--c),var(--o));
 color:#fff;
}
<div class="box">
  some content
</div>


来源:https://stackoverflow.com/questions/50704177/css-variables-and-opacity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!