JavaScript30 - Day 3

By Camilla Krag Jensen naxoc |

Day 3 of #javascript30 is using CSS variables and manipulating them with JS. I got my mind blown and I learned about the :root pseudo-element.

CSS variables

The browser support for CSS variables is not great yet. They also have a little bit of a funky syntax with the --:

element {
  --spacing: 10px;
}

That said, I got pretty excited about the cool stuff you can do with them together with JavaScript. I can't wait for better adoption for them but there are hopefully also some polyfills for them out there.

Here is what blew my mind. You can manipulate the variables from JavaScript and the browser updates the CSS. Like this for instance:

var spacing = 12;
document.documentElement.style.setProperty('--spacing', `${spacing}px`);

Boom! I can potentially update hundreds of CSS properties with that line of JavaScript. Nice!

:root pseudo-element

I also learned about the :root pseudo-element. CSS variables declared there are global but you can override variabels on any element on the page like you are used to. CSS still cascades.