How to apply transparency in CSS color variable?
P粉348088995
P粉348088995 2023-08-20 18:51:07
0
1
462
<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>
P粉348088995
P粉348088995

reply all(1)
P粉458725040

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! ), use var() to replace that value with the rgba() function with the desired alpha value and it will work correctly:

:root {
  /* #f0f0f0转换为十进制RGB */
  --color: 240, 240, 240;
}

body {
  color: #000;
  background-color: #000;
}

#element {
  background-color: rgba(var(--color), 0.8);
}
<p id="element">如果您能看到这个,说明您的浏览器支持自定义属性。</p>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template