Changing Variable Dynamically (At Runtime) via Less and CSS

Dynamically changing less variables

The creator of less.js added some features that should allow you to do something like this. Read the comments and the answers here: Load less.js rules dynamically

Manipulating LESS variables dynamically

What you are looking for is a dynamic way to modify LESS variables. You can do it using less.modifyvars().

Call it when the user clicks on the particular color and set the color to the variables. LESS changes the value of the variable and automatically renders the CSS again with the changed values.

How to change less variables color theme dynamically as per users choice

Less is a CSS preprocessor which means that it produces CSS at compile-time, not runtime. Therefore you can't do what you are aiming to do.

You can have a look at css variables if you want to dynamically override it. You can also use a CSS in JS or make smart use of the CSS cascading model.

Change SASS or LESS variable value at runtime

If you're targeting only users with modern browsers, CSS has experimental variable support (see Can I use.. data). Here's an example of from MDN:

:root {
--main-bg-color: pink;
}

body {
background-color: var(--main-bg-color);
}

If you took this approach, you would only have to insert the colour variable into a simple stylesheet, and CSS would do the rest:

<style>
:root {
--group-colour: {{ groupColour }}
}
</style>
<link rel="stylesheet" href="/path/to/stylesheet/with/variables.css">

For more information on CSS variables, see MDN's CSS var() documentation.

dynamically change LESS variables in page with JavaScript

Instead of doing the variable replacing client-side, since I was doing it in a Rails app anyway, I moved it server-side. I'm using the Ruby bindings for LESS to parse some LESS that includes my custom variables, rendering the parsed result with content_type: 'text/css' and using an AJAX request to add a stylesheet link to the rendered CSS.



Related Topics



Leave a reply



Submit