How to apply transparency in CSS color variable?
P粉348088995
2023-08-20 18:51:07
<p>I'm designing an app in electron so I can access CSS variables. I defined a color variable in <code>vars.css</code>: </p>
<pre class="brush:css;toolbar:false;">:root {
--color: #f0f0f0;
}
</pre>
<p>I want to use this color in <code>main.css</code> but apply some transparency: </p>
<pre class="brush:css;toolbar:false;">#element {
background: (somehow use var(--color) and set some transparency);
}
</pre>
<p>How do I do this? I'm not using any preprocessor, just CSS. I'd prefer a pure CSS answer, but I'm also open to JavaScript/jQuery solutions. </p>
<p>I can't use <code>opacity</code> because I'm using a background image that shouldn't be transparent. </p>
You cannot apply an alpha channel to an existing color value. That is, you cannot add an alpha component to an existing hexadecimal value (e.g.
#f0f0f0
) and use the resulting value with another attribute.However, the custom property allows you to convert the hexadecimal value to an RGB triplet for use with
rgba()
, storing the value in the custom property (including the comma! ), usevar()
to replace that value with thergba()
function with the desired alpha value and it will work correctly: