DRYer CSS with Less written by: Lee Richmond posted on: 22 February 2010
One thing I have disliked for a while about web development is CSS (Cascading Style Sheets). We all love to have web apps that look pretty but when it comes to writing CSS you tend to find that you end up repeating values and this is what I dislike about it.
There are various solutions to deal with this problem such as Sass but in most cases this means taking the time to get used to a new syntax. Luckily I found this Less, Less is a way of DRYing up your CSS using Variables and Mixins without taking the extra time to learn a whole new syntax.
Less is easy to install assuming you have RubyGems installed simply type:
1 2 |
sudo gem install less |
Nesting
Nesting with Less couldn't be simpler in your old CSS you may have something along the lines of:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
body{ font-family: arial; font-size: 13px; color: #000000; } body #header{ width: 960px; height: 100px; margin: 0 auto 0 auto; } body #header .navigation{ width: 400px; height: 50px; float: left; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
body{ font-family: arial; font-size: 13px; color: #00000; #header{ width: 960px; height: 100px; margin: 0 auto 0 auto; .navigation{ width: 400px; height: 50px; float: left; } } } |
Variables
Once again these help to tidy up your CSS by allowing you to declare elements such as colors etc. at the top of the file like so:
1 2 3 4 5 6 7 8 |
@main_color: #CC0000; @header_margins: 0 0 0 10px; h1{ color: @main_color; margin: @header_margins; } |
Mixins
Say for instance you use rounded corners on various elements in your layout, mixins can be extremely helpful in making sure we not only cut down on the amount of code we have to write but keeping things consistent for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
.rounded_corners (@radius: 5px) { -moz-border-radius: @radius; -webkit-border-radius: @radius; -khtml-border-radius: @radius; border-radius: @radius; } .article{ .rounded_corners; } .submit_button{ .rounded_corners(10px); } |
Finally to convert your .less file to a working .css file to be used on your application simply type the following in to the command line:
1 2 |
lessc public/stylesheets/style.less |
I have only covered the basics of what you can do with Less hear but make sure you head over to http://lesscss.org and give it a try for yourself.
*UPDATE* For Textmate users there is a bundle you can install to make life even easier for yourselves http://github.com/appden/less.tmbundle



