I’ve recently started using LESS (an extension of CSS that adds variables, mixins, operations, and functions) and I think I’m in love. I was initially hesitant, but diving in and giving it a go was such a pleasant experience—I won’t be going back to pure CSS anytime soon. Biggest selling point? Nested rules, by far.
Features
Here’s a quick run-down of the features of LESS that made me giddy. Features I won’t be mentioning are operations, color functions, and namespaces.
Nested Rules
This is what sold me on LESS. Gone are the days of trying to remember which class name should come first—and the frustration that out-of-order declarations cause. Inheritance is now simple and clear!
Pseudo classes (:hover, :after, etc) can be placed inside of their parent class, as expected. I almost always define hover states for links, and I love having only one root-level class declaration for them now.
#header {
h1 {
font-size: 18pt;
font-weight: bold;
}
p {
font-size: 12pt;
a {
text-decoration: none;
:hover {
border-width: 1px;
}
}
}
}
Variables
LESS gives you variables (technically constants, since they can’t be redefined) that are prefixed by an ampersand. Very useful for color definitions.
@color: #4D926F;
#header {
color: @color;
}
Mixins
If I were writing LESS, I would call these functions. They are defined almost like CSS classes, except they take in parameter values (which can have a default value). I found these to be particularly useful for eliminating all of those annoying “vendor prefix” blocks.
.rounded-corners (@radius: 5px) {
border-radius: @radius;
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
}
#header {
.rounded-corners;
}
#footer {
.rounded-corners(10px);
}
Isn’t this a JavaScript library?
Yes. Does this mean you should use it as a client-side JavaScript library? Absolutely not!
It took me over a year to look into LESS because of that misunderstanding. I thought this was one of those newfangled web development trends that pushed everything onto the client (which I hate, as it doesn’t obey the practice of progressive enhancement). Enter Node.js—and we can include the LESS to CSS conversion step in deployment.
gem install less
Issue the above command to install the gem, which will give you the lessc executable. If you’re using TextMate, you might be interested in this bundle which includes syntax highlighting and an overwrite of the save key code to compile your .less to .css.
Since I’m using Jekyll as a blogging platform, I use a simple plugin to compile my .less files to .css files as the site is generated.