0

I have :root css variable --color: #ff0000;. I use hex codes, not rgb/rgba. I am trying to make this color variable opacity: .2;. But I can't get it to work.

I tried this and some other options. How can I put opacity on a HEX css variable?

tr {
    background: rgba(var(--theme-color), 0.2);
}
floriankapaun
  • 472
  • 1
  • 4
  • 19
Some Name
  • 561
  • 6
  • 18

2 Answers2

1

When you do

:root {
  --theme-color: #ff0000;
}
tr {
    background: rgba(var(--theme-color), 0.2);
}

The browser is just taking that literally. You end up with

tr {
    background: rgba(#ff0000, 0.2);
}

which is invalid syntax for rgba. If you open your browser console and inspect the styles, you'll see that it's invalid.

You have a few options:

  1. Get the rgb equivalent of your hex color and use that instead. In your case, the rgb equivalent of #ff0000 is 255, 0, 0, so you could do rgba(255, 0, 0, 0.2).

  2. Set the opacity in 8-character hex form. See Hexadecimal color code for transparency. In your case it'd be #ff000033.

  3. If you are using a preprocessor like Sass, you can use a color function to programmatically set the value from the opaque color you have in a variable. For example, Sass has the transparentize function. Other preprocessors have equivalents, so you can Google for that.

  4. Use the actual CSS opacity property.

    tr {
      background: var(--theme-color);
      opacity: 0.2;
    }
    

    Note, however, that this isn't strictly the same as changing the alpha value in a background-color. Opacity affects the entire element and its children, so you may have to change how you do your HTML/CSS to pull off the same visual effect.

cjl750
  • 4,380
  • 3
  • 15
  • 27
  • Sadly for this project 1, 2 and 4 are not an option. I did not know Sass had a transparentize function, that may be an option! Maybe I can make a mixin for that. – Some Name Feb 27 '23 at 19:23
0

It does actually work like this:

:root {
    --color: 255,255,0;
  }
  body {
    background: rgba(var(--color), 0.5) !important;
  }
digitalniweb
  • 838
  • 1
  • 7
  • 15