DEV Community

Arnav Bansal
Arnav Bansal

Posted on

Can CSS color variables depend on each other? Help me fight off CSS preprocessors.

Here, --dark-highlight is a brighter version of --dark. Is there a way I can set --dark-highlight to be dependent on --dark, where it automatically uses the same hue, saturation, and alpha values, but increases the lightness by 5%

:root {
  --dark: hsla(209, 28%, 6%, 1);
  --dark-highlight: hsla(209, 28%, 11%, 1);
}

Also, what's a good guide to the new CSS features?

Top comments (4)

Collapse
 
link2twenty profile image
Andrew Bone

You can do something like this

div {
  --h: 209;
  --s: 28%;
  --l: 30%;
  --a: 1;
}

div:hover {
  --l: 60%;
}

div {
  background: hsl(var(--h), var(--s), var(--l), var(--a));
}

Now when you hover over a div the lightness value will change, alternatively, you could do something like this.

div {
  --h: 209;
  --s: 28%;
  --l: 30%;
  --a: 1;
}

div:hover {
  background: hsl(var(--h), var(--s), calc(var(--l)*2), var(--a));
}

div {
  background: hsl(var(--h), var(--s), var(--l), var(--a));
}

This will achieve the same result but calculates the new lightness meaning you can use classes to have different values.

Here it is in action jsfiddle

Collapse
 
rhymes profile image
rhymes

No, as far as I know CSS variables are meant to store simple values, not functions.

You need mixins for something that advanced: sass-lang.com/documentation/file.S...

SASS/SCSS mixins can have arguments with default values, and you can easily accomplish what you're asking.

You need the SCSS preprocessor though.

Collapse
 
bhaibel profile image
Betsy Haibel

Andrew Bone's solution will work, but I can't really recommend it.

CSS "variables" are really CSS custom properties, and I wish the terminology around them weren't so misleading because it leads folks into the exact dilemma you're running into right now. You can't and shouldn't use CSS custom properties like you would use variables in SCSS or Less -- but because they're "variables" folks try anyway.

CSS custom properties are intended to set meta-properties for larger components. For example:

.tabs--primary {
  --tab-color: green;
}

.tabs--secondary {
  --tab-color: aquamarine;
}

.tabs {
  background-color: var(--tab-color);
}

This gets super important once you start working with web components and Shadow DOM -- custom properties turn out to be the only real way for web components to expose styling hooks to the page that's using them. In that context, the way that custom properties use the cascade, and the way that they're limited, is actually super appropriate!

But if you're looking for a full-fledged variable system, a preprocessor is still your best bet.

Collapse
 
desolosubhumus profile image
Desolo Sub Humus 🌎🌍

I'm not entirely sure of what you're trying to do, but this might help. dev.to/desolosubhumus/using-css-fi...