Nifty trick with CSS-variables

Nifty trick with CSS-variables
Photo by Simon Schwyter / Unsplash

I was playing around with a list of links that could have three different states depending on whether the item was active or not. It was a bit more complex than what is shown below, but as it involved multiple values. And some needed to be the same, however at one moment I realized that I could do it much simpler using CSS-variables.

.list {
  --color-default: red;
  --background-default: green;
  
  --color-active: green;
  --background-active: blue;
  
  --color-hover: blue;
  --background-hover: red;
}

.list-item {
  --color: var(--color-default);
  --background: var(--color-default);
  color: var(--color);
  background-color: var(--background);
}

/* Here we list the manipulations */
.list-item.active {
  --color: var(--color-active);
  --background: var(--background-active);
}

.list-item:hover {
  --color: var(--color-hover);
  --background: var(--background-hover);
}

This might not seem all that special, but with this it becomes a whole lot easier to manage a complex components without having to search my style sheets to find all the variables.

And it becomes even more useful once you start using relative color functions.

/* Every item should have muted color relative to the background */
.list-item {
  border: 1px solid color-mix(in hsl, var(--background), black 10%);
}

Now each item has muted background color and if I want to change the style all I need to do is override it in one place.