Cleaning up CSS with LESS

LESS

I’ve spent the past couple days porting over Popcorn Maker’s CSS to use LESS, a scripting language for cascading style sheets.  It offers convenient features that help overcome some of the inherent limitations of CSS, particularly its lack of modularity. LESS is also a superset of CSS, so any valid CSS code is valid LESS code, reducing the learning curve to maybe an hour of playing around with it. 

Mixins

By far the most useful feature of LESS is the mixin. A mixin is just a fancy word for an equivalent function or method in other languages. It lets you define a set of rules and gives you an easy way to access those rules without writing them out each time you need them. Say we needed to restrict the user from selecting text. The CSS for that would be:

If I wanted to make the text on multiple elements unselectable I’d have to copy that same chunk of code for each element. With LESS I can turn the above code into a function and call that function by its name. Here’s how it looks in LESS:

When converting LESS code to CSS, LESS will replace every instance of  .selectNone; with the CSS I defined in the  .selectNone() function. Useful!

But it gets even better – LESS lets you make functions with parameters, too. In Popcorn Maker, we have multiple instances where we need to make something transition all fancy-like. We’ll have:

but with a different property or duration for different elements. With LESS, I was able to make a function that accepts two parameters – a property and a duration – and call that function wherever I needed a transition. Here’s what it looks like:

This significantly reduced the size of our CSS file and made it a lot more readable. There are other great features but I won’t cover them here. I highly recommend LESS to anyone looking to modularize their style sheets.

Leave a Reply

Your email address will not be published. Required fields are marked *