In Css, Development, Html, Jquery, Tutorials by |

This article demonstrates how to use the less.js framework and jQuery, to define CSS themes in a static webpage and dynamically applying them on the browser side.

In previous articles, I wrote about dynamically reloading CSS stylesheets in a webpage using Javascript and jQuery.
However, I was never satisfied with some of the limitations of CSS, for instance in terms of lack of variables. For example, if one uses the same colour many times in the same stylesheet, one has to copy that colour over and over. The less.js framework provides a dynamic language. LESS extends CSS with dynamic behaviour such as variables, mixins, operations and functions. In this example I will show the use of variables and dynamic loading of files to apply themes to a website.

I didn’t bother looking for a CSS theme framework. I just explored the possibilities for having a neat CSS design and being able to dynamically reloading it using jQuery.

In the markup, we define a button bar that will allow us to switch themes.

Now, the stylesheet files for the less.js framework. We define a base.less theme, and separate files for the themes: gray.less, red.less and purple.less. The default theme is purple, as you can see in the markup above.

The base file defines the stylesheet for the markup. Variables are defined for colours and fonts. In the theme files, these variables are overridden.

This is an example theme file that overrides the base variables

The remaining part is the Javascript. Using jQuery, the less script is replaced when a click happens on one of the links on button bar. We remove the CSS file generated by Less and call refresh() to rerun the less.js compiler.

Have fun!

Download

Demo

Css code image via Shutterstock.

 

I'm a software developer interested in mostly web application development and Java. During the last few years I've developed an interest in the Grails framework as well as in JQuery.