Can I inject Database values into CSS


I am working on a site in which I want to allow basic themeing based on the user logged in.

Essentially I just want to store some image urls and colours in MongoDB and then have these values inserted into the correct places in my code. The image urls are fairly straight forward I think.

However I also want a nice clean way of changing colours across the site. I will be setting up my css so there are theme classes in place on relevant elements so really I just want to change the style definitions to change the colour.


.bgColour1 {
   background-color: red;

what I really want is:

.bgColour1 {
   background-color: <VARFROMDB>;

Then throughout the site the bgColour class will reflect the user’s choice for bgColour1.

Before Meteor I would have done this inside <style></style> tags in the head.

I’ve looked at pre-processors like LESS and SASS but I don’t think they suit the “on the fly” nature of this exercise.

Any help would be much appreciated.


1 Like

You’ll be able to do this with CSS Variables once they’re supported in more browsers:

In the meantime you can programmatically insert <style> elements into the <head>, which will be interpreted on the fly. For instance something like this should work:

var $style = $("<style type='text/css'></style>");
$style.text(`body { background-color: ${varFromDb};`);

It would be interesting to make a package that makes this reactive and declarative!


If you have a predefined set of styles, you can just define these in CSS and then apply the class names dynamically. Even if you’re doing lots of mix and matching, just break up the classes into small components and apply them piecemeal.

eg: class=“redBg blueBorder whiteFont”

If you’re creating urls or styles dynamically (for bg images and such), you can apply the styles inline and use handlebar variables that way. If you want them applied to your whole site, just apply them to container level elements.

Thanks rahul

That solution should do nicely. Will try it out!

Surprising that Meteor does not support CSS manipulation out of the box since it parses all files anyway.

pcm, yes the handlebars solution could work, it’s just I think it is easier to manage, if elements and containers are only styled via class references rather than inline styling. Which is why i’d rather modify the class definition! :grin:

Thank you both for answering :star:

Hm, you could use something like

You could use SASS with

GrooveUI allows on the fly modification of SASS variables.


You can use styled components for this. (If you use React)

It is integrated into our router with SSR built in (not for data depending on user tho)

You’d have to use the develop branch but I can help you with it.