Typically, a central CSS file sets the foundation for styling elements that remain constant, while additional CSS files are used to apply different themes. Each theme has its own separate CSS file. When constructing a webpage, only one of these theme files needs to be linked using a link
element.
To enable the ability to switch themes dynamically, you can achieve this by simply adjusting the href
attribute of the link
element.
For example, if we have a link
tag like this:
<link id="themeStyle" href="green.css" rel="stylesheet">
The following code snippet can change it to a different theme:
document.getElementById("themeStyle").href = "blue.css";
Check out the live example: Live Demo | Source Code
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<link id="themeStyle" href="/acofoy/1" rel="stylesheet">
</head>
<body>
<div id="group">
<div><label><input name="theme" type="radio" value="1" checked>Green</label></div>
<div><label><input name="theme" type="radio" value="2">Blue</label></div>
<div><label><input name="theme" type="radio" value="3">Red</label></div>
</div>
</body>
</html>
JavaScript:
(function() {
var buttons = document.getElementById("group").getElementsByTagName("input");
var index;
for (index = 0; index < buttons.length; ++index) {
buttons[index].onclick = setStyle;
}
function setStyle() {
document.getElementById("themeStyle").href = "/acofoy/" + this.value;
}
})();
Note: I used numbers for the values rather than names because I was using JSBin. In real life, of course, I'd use names like green.css
, blue.css
, red.css
, etc.