Saturday, November 5, 2011

Overcoming CSS's limitations with Less CSS

I have written my fair share of CSS for almost every kind of project. CSS is easy to use but on a whole I always wished that CSS had some kind of programming elements. You dont' how many times I have come across a scenario where I had to write a style rule over and over again or target specific children classes inside a parent element. The resulting CSS is not pretty. This was until I came across Bootstrap from Twitter and Less CSS. The tag line says:
LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions. LESS runs on both the client-side (IE 6+, Webkit, Firefox) and server-side, with Node.js.
Yes, CSS with "dynamic behavior" and everything still boils down to pure CSS. You just drop in less.js and off you go. Here's an examples that I think makes writing CSS interesting again. Supposed that you have a hex colors that is used all over the place, this wouldn't be a problem until you have change it. Now you can crank up your editor's Find and Replace but we know that sometimes that thing replaces values that it shouldn't be replacing. So....
/* Less CSS sheet */
@color: #4D926F;

#header {
  color: @color;
}
h2 {
  color: @color;
}

The variables @color allow me to specify widely used values in a single place, and then re-use them throughout the style sheet, making global changes as easy as changing one line of code. With a little foresight, I can set this up so what I change say only affects #header divs or certain areas in my HTML page. Don't worry because, when you pass the site to the browser, your Less CSS will be "compiled" by the less.js spitting out pure, clean CSS.
/* Your CSS as far as the browser is concern */
#header {
  color: #4D926F;
}
h2 {
  color: #4D926F;
}

I think this will become another important tool in a web developers toolbox. I already use it indirectly anyway. I'm a big fan of the Bootstrap framework from Twitter.