Sinan Aksay smiling with cool shades

on February 04, 2020

Editing CSS variables with JS

javascript1 min read

CSS variables are pretty cool. You probably know you can define one like this:

:root {
  --donny-brand-color: purple;

and then use it somewhere else later:

.donatellosMask {
  background: var(--donny-brand-color)

But did you also know that you can modify or create CSS variables from JS side? You can do this using setProperty method any element’s (in this case documentElement since we defined the variable on :root scope) .style interface.'--donny-brand-color', 'red')

This is especially useful when you need to tie some style properties to event listeners, like setting the position of an element to current cursor position. See this example on codepen which brings everything together:

Discuss on TwitterEdit on GitHub

Enjoyed this article?

Get new ones
in your inbox!

No spam. Unsubscribe whenever.