Simplify Your CSS With LESS Elements

less elements logoI’m a big fan of LESS, the CSS pre-processor. Many of the people who learn about it immediately see its potential to make their CSS development easier, however, some express doubts–they just don’t see how extending CSS functionality helps since they can do everything using vanilla CSS.

One of the big ways LESS helps–probably the biggest–is through something called mixins, that is, being able to re-use classes inside other rulesets. This is especially helpful with browser specific CSS code (e.g. having to use -webkit-border-radius, -moz-border-radius and border-radius for the same property). Having to write out at least 3 lines of code every time you want to use a CSS3 property makes your code bloated and difficult to update.

To help with this I’ve developed a set of mixins I commonly use throughout my code. I’m calling this set LESS Elements, and I’ve put it up on its own site over at lesselements.com.

To better illustrate what the mixins are let me show you an example. Imagine we want to add rounded corners to the top left and top right edges of a div. Our vanilla CSS code will look like this:

#some_div {
  -webkit-border-top-left-radius: 5px;
  -webkit-border-top-right-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-topright: 5px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}

LESS Elements has a mixin called .border-radius, which lets us compress the above 6 lines of code into just 1:

#some_div {
  .border-radius(5px, 0, 0, 5px);
}

Looks like standard shorthand CSS, with each of the values representing border radii in a clockwise rotation: top right, bottom right, bottom left and top left. Compiling this LESS code will produce the exact same CSS as the previous example, but now it’s just 1 line of code. Simpler to write, and much easier to update.

Head over to the site to grab the code and learn about the other mixins in the set. If you find it useful and have some ideas for other mixins to add please drop me an email–or let me know by posting a comment below.