Do More With Less
03/24/2012
We recently completed a website that required us to use Bootstrap and LESS. Bootstrap was something we had used in the past, but without LESS, so we were really excited at the opportunity to give LESS a try.
LESS is a dynamic stylesheet language that extends CSS with dynamic behaviors. In short, it’s awesome and I can only hope some of the capabilities of LESS make it into CSS 4.
Why is it so great? Let’s walk through some examples of how we used LESS on our latest project.
Variables
A variable is anything you want to repurpose or reference throughout your CSS. It could be a color value, image, etc. We used variables as a quick way to reference our client’s brand colors. Doing that gave us the flexibility to dramatically change the look of elements in the website with ease.
Here’s an example of a header bar that’s driven by variables for a color and image:
Operations
The dynamic nature of LESS becomes more obvious in the use of operations, which allow you to add, subtract, divide and multiply values. While we didn’t use operations a tremendous amount, here’s an example of altering the width of a DIV using an operation:
Functions
LESS comes with a variety of functions, which we used quite a bit to define color variances based on the branding colors. For example, we could lighten or darken a color like so:
Mixins
One of the most powerful things about LESS is the ability to create Mixins. You can define a set of rules that can be repurposed throughout your CSS. While we used Mixins pretty heavily, I feel like we just scratched the surface in terms of the full capabilities of what you can do.
Here’s a simple Mixin that applies a drop shadow to a given element:
This example alone shows how powerful LESS can be. I don’t have to write the same prefixed properties over and over whenever I want to add a drop shadow to an element.
What if I want to repurpose the Mixin, but change a value just for one instance? That’s where you can construct a Parametric Mixin to accept parameters:
Now, anytime I want to use the drop shadow I can also alter the parameters for a given instance.
By far, one of the most complex examples of how we used a Mixin was defining a elliptical gradient that had a repeating image layered on top of it. This Mixin accepted parameters for two gradient colors and an image.
Even though this example may seem fairly complex, it feels like we only just scratched the surface on the capabilities of LESS. Bootstrap is a great way to start putting a website or prototype together and the LESS version of Bootstrap makes it even more powerful.
In fact, a great way to learn more about the capabilities of LESS is to download and look at the LESS version of Bootstrap. Check out the Mixins, Utilities and Variables LESS files.
Of course, there’s also a ton of helpful information on the LESS website.