Trying to find ways to prototype new CSS features can sometimes be tricky. Some people choose the route of building (or writing plugins for) a CSS preprocessor for experimenting, some people design and parse new custom syntaxes, and still others write 100% JavaScript solutions to demonstrate the features or functionality they are trying to research.

For my CSS extension experiments in 2018 I think I've figured out the easiest way to prototype and test things out: Event-driven virtual stylesheets.

How to use an event-driven virtual stylesheet

  1. Create a <style> tag in DOM, or empty CSS stylesheet in CSSOM
  2. Populate that <style> tag or CSSOM stylesheet with a string containing CSS
  3. This string can be a JS string, the output of a function, a JS template string, or a combination of these.
  4. Manage event listeners (and/or observers) that reprocess the styles when a specific event occurs (on a specific element, if you want)

To do step 1, 2, and 4, I can use something like: to create and populate a <style> tag based on events.

To do step 3 I can write a stylesheet like this, which is a function that holds a JS template string with CSS text inside:

Notice I was able to easily extend this stylesheet by importing a helper function called 'jsincss-element-query' that provides some simple tests for using element queries:

Using this kind of setup it's very simple to extend CSS using vanilla JavaScript plugins, and by splitting the 'stylesheet-populating, event-listening' logic from the helper function logic it also helps keep the helper functions very small and quick to prototype!

Here's a lightweight element query demo built using these methods:

And here's all the setup that was required to get the JavaScript-powered styling working:

  import jsincss from '//'
import stylesheet from './element-query-test.js'
import scrollStyles from './element-query-scroll-test.js'

jsincss(scrollStyles, ['[class*="-scroll-"]'], ['scroll'])

  • import the jsincss function
  • import the main stylesheet function (which itself imports jsincss-element-query)
  • import the scroll styles function (which imports jsincss-element-query)
  • apply the main styles with default options (watching load, resize, input, and click on window)
  • apply the scroll styles with a custom event (watching scroll on all [class*="-scroll-"] elements)

2,399 0 8