css: sharing variables with javascript

2021-08-12

 | 

~1 min read

 | 

188 words

I wanted to use a CSS property as an input into some javascript recently and so I wondered if it was possible to share the value rather than redefine it in both locations.

It turns out we can, and it’s done by using the @value decorator in a CSS module (h/t Josh Johnston in this GitHub issue).

A straight forward example:

styles.css
@value faveColor: #F0F;

.box {
  border: 1px solid faveColor;
}
index.js
var styles = require("./styles.css")
console.log("My favourite color of all time is", styles.faveColor)

We can also use this for some redirection. For example, what if we have a shared set of sizes that we want to use in our javascript, but don’t have any classes (maybe because it’s only one size that’s being applied)?

style.css
@import "../sizes.scss";
@value fontLarge = $font-large;

This is now available for use in Javascript in the same way as above.

index.js
var styles = require("./styles.css")
console.log(`large fonts are ${styles.fontLarge}`)

In this example we could have just defined the @value in the sizes.scss and imported that in the index.js (as we didn’t actually use the value in style.css).


Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!