How to apply transparency to CSS color variables?
P粉573809727
P粉573809727 2023-10-13 15:48:04
0
1
567

I'm designing an app using Electron so I can access CSS variables. I defined a color variable invars.css:

:root { --color: #f0f0f0; }

I want to use this color inmain.cssbut with some opacity applied:

#element { background: (somehow use var(--color) at some opacity); }

How should I do it? I'm not using any preprocessor, just CSS. I'd prefer an all-CSS answer, but I'll accept JavaScript/jQuery.

I can't useopacitybecause the background image I'm using shouldn't be transparent.

P粉573809727
P粉573809727

reply all (1)
P粉615886660

You cannot take an existing color value and apply an alpha channel to it. That is, you cannot take an existing hexadecimal value (such as#f0f0f0), give it an alpha component and use the resulting value with another property.

However, the custom property allows you to convert the hexadecimal value to an RGB triplet for use withrgba(), storing the value in the custom property (including the comma!) , use thevar()function to convertrgba()with the desired alpha value, and it will work:

:root { /* #f0f0f0 in decimal RGB */ --color: 240, 240, 240; } body { color: #000; background-color: #000; } #element { background-color: rgba(var(--color), 0.8); }

If you can see this, your browser supports custom properties.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!