0

I am defining a color set for a small project. I want to define custom properties for a range of hsla() colors but be able to vary the opacity of those colors. Should I be able to do something like this:

:root {
  --clr-900: hsla(36, 83%, 0%, var(--opacity, 1));
  --clr-700: hsla(36, 83%, 30%, var(--opacity, 1));
  --clr-300: hsla(36, 83%, 70%, var(--opacity, 1));
  --clr-200: hsla(36, 83%, 85%, var(--opacity, 1));
  --clr-100: hsla(36, 83%, 100%, var(--opacity, 1));
}

The theory is if I apply just the property, I get an opacity of 1. If I set the --opacity custom property, it would change the opacity:

.test1 {
  background-color: var(--clr-900);
  // hsla(36, 83%, 85%, 1)
}

.test2 {
  --opacity: 0.65;
  background-color: var(--clr-900);
  // hsla(36, 83%, 85%, 0.65)

When I try this, I always get the fallback value (1) rather than resolving var(--opacity) when present.

Tim R
  • 43
  • 7

1 Answers1

1

CSS variables don't work in the way that you are trying to use them. Variables that are defined with other variables only take variables on the same level or levels above them.

A nice "hack" that I found was, instead of using the :root selector, use the universal selector * to define the varibales on all levels. That way, since you define the color variables on the same level, changing the opacity variable works. Keep in mind that this might cause some unwanted results, and if you want to consider other solutions, these might help you:

CSS scoped custom property ignored when used to calculate variable in outer scope

Overriding :root CSS variables from inner scopes

* {
  --opacity: 50;
  --clr-900: hsla(36, 83%, 0%, var(--opacity, 1));
  --clr-700: hsla(36, 83%, 30%, var(--opacity, 1));
  --clr-300: hsla(36, 83%, 70%, var(--opacity, 1));
  --clr-200: hsla(36, 83%, 85%, var(--opacity, 1));
  --clr-100: hsla(36, 83%, 100%, var(--opacity, 1));
}

.test1 {
  background-color: var(--clr-900);
}

.test2 {
  --opacity: 0.65;
  background-color: var(--clr-900);
}
<p class="test1">hello world</p>
<p class="test2">hello world</p>
fabian
  • 268
  • 3
  • 15