Sitemap

Accessing and modifying CSS variables with Javascript

And why it’s better than SASS variables

2 min readSep 1, 2017

--

Variables in SASS have been around for a while. They allow you to define a variable once at runtime and use that variable in multiple places. Coolness level 3. Coolness level 6? ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓

Interacting with CSS variables with JS post-runtime.

In this demo we are going to build a simple form that will use JS to dynamically update CSS variables(in our case change color and margin of a dot)

Press enter or click to view image in full size
Image
jsfiddle result

JSFiddle Demo

Let’s look at the moving pieces here:

CSS

Press enter or click to view image in full size
Image
css with root vars

Here is some info on CSS :root, here too. From MDN:

The :root CSS pseudo-class matches the root element of a tree representing the document. In HTML, :root represents the <html> element and is identical to the selector html, except that its specificity is higher.

The CSS vars are defined in the :root and applied on lines 13–14. -- is the CSS standard for variable definition.

HTML

Press enter or click to view image in full size
Image
form markup

Straightforward here, note the attributes on the type="range" input. These hold our min and max values as well as our initial value. Same for type="color" input. The initial color value = #2cba92.

JAVASCRIPT

Press enter or click to view image in full size
Image
js accessing css vars

Line by line here:

  • 4 — grab footer element
  • 5 — grab NodeList of all inputs on the page
  • 7 — input CHANGE EventListener
  • 8 — input MOUSEMOVE EventListener(updates dynamic margin on slide)
  • 10 — fn to set the value of the desired CSS var(note we add px to the margin var…

--

--

Ben Garrison
Ben Garrison

Written by Ben Garrison

Technology and Humans. Javascript. Motivation. Positivity. Gratitude. Patience.

Responses (6)