P粉4587250402023-08-21 13:13:49
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>