For more tips like this, sign up to the weekly newsletter!

Use CSS variables to communicate between JS and CSS

Using Javascript, you can read the properties of HTML elements that are set by CSS, and you can also manipulate them. For example, you can read an element's width and set another element's height based on that.

But this is usually cumbersome and kind of a hack.

But with CSS variables, you can define a rudimentary API between the two worlds. These variables can be set on any levels and they propagate down the HTML tree.

To use a CSS variable, use the var(...) keyword. For example, to change the color of an element by a degree defined in some ancestor element:

filter: hue-rotate(var(--hue-rotate));

This uses the --hue-rotate variable.

To set this variable from Javascript, you can set a style property of the body element:

document.body.style.setProperty("--hue-rotate", `${value}deg`);

When this code is run, the browser automatically refreshes the color.

To get the current value, use the getComputedStyle function and get the property by name:

getComputedStyle(document.body).getPropertyValue("--hue-rotate")

You just need to make sure you handle the initial case when there is no value. One way to do it is to initialize it in CSS:

:root {
  --hue-rotate: 0deg;
}

Or handle the empty case from Javascript: value || "0deg".

Try it
References
Learn more: