Reputation: 51978
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.
Upvotes: 5
Views: 9055
Reputation: 13645
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:
<body id="red">
and have css prefixed with this id. So #red myelement.myclass{}
or something. Then switch the ID with javascripts.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.
Upvotes: 11
Reputation: 92324
Benjamin's suggestion was one of my suggestions. The other less known trick is that you can set a disabled property on a stylesheet and that will disable that style sheet
Say you have two stylesheets
<link rel="stylesheet" type="text/css" href="blue-theme.css" id="blue-theme"/>
<link rel="stylesheet" type="text/css" href="red-theme.css" id="red-theme"/>
You can easily enable just one of them
function setTheme(theme) {
var themes = ["blue-theme", "red-theme"];
for (var i=0; i < themes.length; i++) {
var styleSheet = document.getElementById(themes[i]);
if (themes[i] == theme) {
styleSheet.removeAttribute("disabled");
} else {
styleSheet.setAttribute("disabled", "disabled");
}
}
}
Upvotes: 6
Reputation: 13360
The easiest way to do this would be to use LESS. A more complicated way, but one that could be more useful if you plan to do this alot, would be to have your css file handled by php or asp.net (depending on your platform) and use code to output the css (making sure to output the proper headers for a CSS file).
Upvotes: 0