JSON in CSS

Avatar of Chris Coyier
Chris Coyier on

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

Jonathan Neal tweeted a heck of a little CSS trick the other day, putting JSON inside CSS and plucking it out with JavaScript. Valid values for custom properties are quite liberal! So this looks for a CSS rule (e.g. a whole block, like #x { y: z; } where the cssText starts with -- (which is not a valid selector, but who cares — you could change it if you want to thisIsJson or something) and then slices out a string that JSON.parse() works on.

I re-typed his example here:

Is this useful?

WELL.

Probably not, like, on a daily basis. But remember that JSONP is still a thing because CORS exists. Chucking some JSON in CSS I would think is another way around CORS. I kinda doubt it will catch on, but it’s possible. Remember not long ago we were talking about using CSS as an API for literal data. Another questionable idea. ;)

I think “putting weird stuff in custom properties” is the new “putting weird stuff in CSS content.”

For example, ya know how there are media queries in JavaScript, à la matchMedia? And, of course, there are media queries in CSS, too. There was a time (and I’m not sure it’s passed) where defining those media queries only once felt like a good idea, so we weren’t maintaining media queries in multiple places. To keep them “in sync” one idea was to define them in CSS and have them swap the value of some CSS content (e.g. @media (max-width: 500px) { body::after { content: "max500"; display: none; } }) then literally watch for that content to change with JavaScript — and you’d know that media query was active. For real! No joke!

And speaking of JSON in CSS, you can chuck straight-up JavaScript in there as well. This isn’t as clever as Jonathan’s extraction because it just yanks the value out and evals it.

Caleb Williams made a Web Worker with CSS.