@mdo

Powered by Fusion

Like CSS3? Use LESS.js

I’ve been using Less.js in just about every project I can lately and I freaking love it. I don’t go hog wild about it though; I’d rather preserve the readability and structure of regular ol’ CSS. That said, I do want to make more complex things easier.

But wait, why use it? Well, for a few reasons really, but most importantly to add variables for repeated values like colors and to simplify the usage of CSS3 values that have vendor prefixes.

So here are a few examples of how I use Less.js. Check them out and feel free to use them in your own code.

// This is a comment
/* This is also a comment */
div.container {
  ...
}

Comments: Less.js brings a small add-on for me, but for some reason I love it.

// Colors
@linkColor: #4bb14b;
@darkGray: #333;
@lightGray: #7f7d79;

Colors as variables: Hex values can be a real headache, especially if you change them often. Use variables instead to save yourself the pain.

a:hover {
  color: darken(@linkColor, 10);
}
// Additional functions: darken, saturate, desaturate,
    and greyscale

Functions: One of my new favorite features is functions in Less.js. I use them on my link hovers. More info

// Declare border-radius for everyone (yay!)
.borderRadius (@radius: 5px) {
  border-radius: @radius;
  -khtml-border-radius: @radius;
  -moz-border-radius: @radius;
  -webkit-border-radius: @radius;
}
.boxShadow (@shadow: 0 1px 3px rgba(0,0,0,.25)) {
  box-shadow: @shadow;
  -moz-box-shadow: @shadow;
  -webkit-box-shadow: @shadow;
}
div.container {
  background: #fff;
  padding: 30px;
  margin: 0 auto;
  .borderRadius(6px);
  .boxShadow(0 1px 3px rgba(0,0,0,.5));
}

CSS3 mixins: With Less.js, you can use what’s called mixins—partials for your CSS.

Have a suggestion? Talk to me on Twitter or shoot me an email.


Questions?

Have a question about this post, Bootstrap, GitHub, or anything else? Ask away on Twitter or in my AMA repo.