Change Theme Colour Scheme values Programmatically

There is a workaround if we use a modern browser css feature: vars in css

Here’s a clone:

https://anvil.works/build#clone:55HOSHJWIBO4NQBD=LDUUVLF3KHQWOCHN2SPF22EL

In this clone I create a :root css element within theme.css:

:root {
    --primary-500: %color:Primary 500%;
    --primary-700: %color:Primary 700%;
    --secondary-500: %color:Secondary 500%;
    --secondary-700: %color:Secondary 700%;
}

Then I replace all other references to %color:Primary 500% with var(--primary-500)

So far so good.

To change one of these css variables dynamically we can use anvil.js

from anvil.js.window import document
varname = "--primary-500"
color = "red"
document.documentElement.style.setProperty(varname, color)

And for the final part changing all components that were defined like

self.button.background = "theme:Primary 500"

instead define them like:

self.button.background = "var(--primary-500)"

:partying_face:

3 Likes