Less is More
What is Less?
CSS is primitive and dumb. You target elements in the DOM with selectors and style them with properties. That’s it. While this simplistic nature results in a much smaller learning curve especially for non-developers (e.g. designers), it also makes it a less powerful language. It prevents you from efficiently doing what you need to do.
Enter Less. Less is a CSS pre-processor. It extends the CSS language with many features that allow you to make the CSS more maintainable, themeable, and extendable. This is especially beneficial when dealing with larger, more complex applications.
You can run Less client-side where your browser, with the help of an additional script file, will convert your Less code into CSS which it can interpret. This is the easiest way to get started and good for use in development. For production, where performance and reliability are important, you should use a pre-compiling tool that uses node.js or a third party library to convert your Less to CSS on the server.
If we wanted to style various elements in the header of an HTML page, we may create CSS that looks like this:
In Less, we can write the same CSS like this:
You can also reference the parent selector within your nested CSS. Instead of writing this:
You can write this:
Being able to nest styles, mimicking the same hierarchical structure in your HTML, allows you to write CSS that is more readable and organized.
Less lets you use variables, more accurately “constants”, in your CSS.
This supports the DRY principle (Don’t Repeat Yourself) and allows you to quickly make changes in a single location.
Mixins provide a means of including properties from one rule-set into another. Assuming we have the following selector:
We can “mix-in” all properties defined by bordered into other rule-sets like this:
Less has countless built-in functions that allow you to transform various styles.
Here you can see how the built-in darken() function is called, resulting in the border color being 20% darker than the @base color.
Rather than include all your CSS in a single file, you can organize your code into smaller units and import them into a main *.css or *.less file.
Arithmetic operations can be applied to any number, color, or variable:
Guards allow you to provide conditional logic to your CSS.
They can also be used, in combination with Less’s looping functionality, to iterate:
Whether you are using Less or its main alternative Sass, CSS pre-processors allow you to write better, more manageable code. Less is also relatively easy to learn. Even if you only end up using a few of the features, the benefits are significant. Less truly makes CSS a first class programming language and I would encourage all developers to use it.