Using LESS CSS To Implement DRY Principle

CSS is painful. Everybody agrees with that. Repeatable colors  and values are everywhere. When you want to change 1 value you need to search and change values that are affecting the style. We could avoid this by using LESS.


LESS provides us a way to organize CSS styles and make it manageable. We could define variables that can be reusable and make the rules consistent.

There are lots of repeating values in CSS, most especially when we are working with multiple browser’s compatibility. To name some:
  • border-radius
  • box-shadow
  • gradient
  • colors
Lets consider this CSS class:

The problem with this is that changing 1 will cause you change the others.  Find and Replace will solve this, but in huge CSS, you can not use this approach.

The Solution:

Let us refactor the CSS class using LESS.

With LESS we can produce much cleaner and more manageable CSS.

How Do We Use LESS CSS

less.js

You need to download less.js @ lesscss.org and include it in a <script></script> tag in the <head> element of your page. This is the JavaScript that converts LESS commands into normal CSS file on the client site. 

Normal CSS File

We can code LESS in normal CSS file. In Visual Studio 2013, you don’t need to name the CSS file as .less.

But if you need full LESS editing features, install Web Essentials. You can separate LESS file and CSS file.

In the HMTL Page

You need to specify the rel attribute to stylesheet/less.


Your thoughts please.