I would recommend you to do something like the following:
- Give the user a pre-defined list of theme colors to choose from (a drop-down maybe). Don't allow for entering any color they wish to, that would be a pain.
- When the select any color append, the color name to the
body as a class using jQuery/JS.
In Less, write the below code, compile it statically and link the compiled CSS to your page.
body {
background-color: red; /* default */
&.red {background-color: red;}
&.green{background-color: green;}
&.blue{background-color: blue;}
}
window.onload = function() {
document.querySelector('#color-chooser').addEventListener('change', function() {
document.body.className = this.value;
});
}
/* compiled CSS based on the Less code provided above */
body {
background-color: red;
/* default */
}
body.red {
background-color: red;
}
body.green {
background-color: green;
}
body.blue {
background-color: blue;
}
<label>Select Background Color:</label>
<select id='color-chooser'>
<option value='red'>Red</option>
<option value='blue'>Blue</option>
<option value='green'>Green (Hex)</option>
</select>
Alternately, if you insist on doing it dynamically via the front-end then you can use modifyVars option:
Note that I wouldn't recommend this option as the Less website itself states that it should be used only when there is no other choice.
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.1/less.min.js"></script>
</head>
<body>
<label>Select Background Color:</label>
<select id='color-chooser'>
<option value='red'>Red</option>
<option value='blue'>Blue</option>
<option value='#0F0'>Green (Hex)</option>
</select>
<script type="text/javascript" language="javascript">
document.querySelector('#color-chooser').addEventListener('change', function(){
less.modifyVars({ /* this sets the color to the variable */
'@bgcolor': this.value
});
});
</script>
</body>
</html>
styles.less:
body {
background-color: @bgcolor;
}
@bgcolor: red;
Plunker Demo (couldn't put this into a snippet)