search

Home  >  Q&A  >  body text

How to apply opacity to CSS color variables?

<p>I'm designing an app using Electron so I can access CSS variables. I defined a color variable in vars.css: </p> <pre class="brush:css;toolbar:false;">:root { --color: #f0f0f0; } </pre> <p>I want to use this color in <code>main.css</code> but with some opacity applied: </p> <pre class="brush:css;toolbar:false;">#element { background: (somehow use var(--color) at some opacity); } </pre> <p>How do I do it? I'm not using any preprocessor, just CSS. I'd prefer an all-CSS answer, but I'll accept JavaScript/jQuery. </p> <p>I can't use <code>opacity</code> because the background image I'm using shouldn't be transparent. </p>
P粉495955986P粉495955986499 days ago499

reply all(1)I'll reply

  • P粉715274052

    P粉7152740522023-08-24 18:50:58

    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 with rgba(), storing the value in the custom property (including the comma!) , use the var() function to convert rgba() 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);
    }
    <p id="element">If you can see this, your browser supports custom properties.</p>

    reply
    0
  • Cancelreply