Updating CSS Variables with Javascript

If you are building an application or SaaS platform, or in fact any website, it can be useful to store all your colours as CSS variables, and then update these once to change the theme of the app.

Fortunately this is relatively straightforward to accomplish. Imagine you have your CSS variables set up like this:

css Copy
:root { --main-background: blue; --main-sidebar: red; /* Yes these colors do not match */ }

:root CSS styles are stored on document.documentElement. So we can access all of its styles via that. So in JS, all we need to do is this:

javascript Copy
document.documentElement.style.setProperty("--main-background", "yellow");
Last Updated Sunday, 27 December 2020
Click to Subscribe Subscribed


Subscribe to stay up to date with our latest posts via email. You can opt out at any time.

Not a valid email