Observable CSS

Since we have views that are reactive to other observable values (cells) I was curious of there were examples on how we can make CSS styles also reactive - the ones that contain and depend on other observable values? I imagine this useful for theming and other variable usage within css?

I’m not sure but I imagine this working like other tagged templates?

css`
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border-radius: 3px;

  /* Color the border and text with theme.main */
  color: ${theme.main};
  border: 2px solid ${theme.main};
`;

Hi @lmatteis - Sorry if I am misunderstanding, but are you just looking to inject values in CSS? This is totally possible!

Let me know if this is what you meant:

1 Like

That’s exactly what I was looking for thanks! How does it work behind the scenes? Does it recreate the <style> tag and appends it to the DOM for every color-change?

Hi @lmatteis -

I am a novice and relatively non-technical user, so I will outline this as best I can and hope others (including you!) will correct me if I misguide you.

First, I created an HTML Observable’s tag template literal html (refer to the Standard Library). In this HTML cell, I created a CSS element using the <style> attribute. From there, I just wrote out my CSS, but instead of the color value I put a placeholder that reference a name cell: ${c}.

Separately, I imported a color selection input from another notebook, and then used that function to render the color picker with viewof. Because I named the cell containing the color information, when I referenced that name cell in the cell containing my CSS attribute, the Observable runtime “knew” it was being updated (refer to How Observable Runs). You can see this relationship in effect as you move around the color selection… there’s a grey bar that appears on the HTML element as you click around the color pallet… that’s evidence that the runtime is updating dependent cells.

Maybe the above is too obscure: More succinctly: the magic is in the runtime.

I made a utility library for this a while ago:

It will recreate the <style> tag whenever any variables change, and it displays a syntax-highlighted version of the CSS code (either directly in the notebook or collapsed by default)

2 Likes