Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change and maintain multiple color themes at runtime with css?

I'd like my web app to have different colored themes:

So now I have:

RedTheme.css
BlueTheme.css

And I load each dynamically at runtime. Depending what user selects in his options menu. And that works, but I don't like having a separate file for each theme.

Option 1. I'm wondering if there's any way I can do something like:

Theme.css?Theme=Red and then within the css to have it figure out which one to use based on that variable.

Option 2. I'm also wondering if maybe I can do something like inside the CSS to do:

background-color: @themeBackgroundColor

and then somehow set this variable at runtime via javascript or something.


If Option 1 and Option 2 are not available, do you have any other suggestions for theming apart from keeping a different file for each theme? b/c maybe I'd like an option where the user can choose custom colors in the future.

like image 779
Shai UI Avatar asked Mar 30 '12 16:03

Shai UI


1 Answers

If you want to use variables in your CSS, have a look at Less or Sass, both have client side solutions for this.

To switch styles you could:

  • Use a ID attribute for the body like <body id="red"> and have css prefixed with this id. So #red myelement.myclass{} or something. Then switch the ID with javascripts.
  • You could have a base CSS file and several theme CSS files on the server side(like gmail does for example) and swap between them with javascript by changing the URL, this would generate a new request in the browser to get the other CSS.
  • You could look for or write some small framework of your own which adds the proper styling inside the html itself as a style attribute (like done here), or which adds inline style elements to the html where you define the custom styles and swap them out with javascript.

Any changes to the CSS of elements or HTML by javascript as far as i've seen will trigger the browser to render the page again.

Changing the CSS files on your clients hardisk directly is not possible since javascript does not allow this. You can however change the CSS in the cache or html.

like image 167
Benjamin Udink ten Cate Avatar answered Sep 27 '22 23:09

Benjamin Udink ten Cate