OdeToCode IC Logo

Keeping CSS Files DRY with .less

Sunday, November 22, 2009

dotless - a LESS css port for .NETIt was just a few weeks ago when I heard of LESS for Ruby, and now there a port for .NET developers: .less (dot less).

One of the frustrating aspects of working with CSS (one of many, actually) is the amount of duplication in a .css file. CSS does allow us to separate content from presentation, but, if I had a nickel for every time I did a search and replace for some hexadecimal RGB code replicated 5 times in a CSS file, I’d buy each of you an interactive t-shirt.

.less help to keep your CSS files DRY using 4 constructs:

  • Variables
  • Mixins
  • Operations
  • Nested Rules

The examples on the .less home page are self-explanatory. For example, variables:

@gold : #cccc99;

body {
  background-color: @gold;

“Mixin” is a Ruby concept, and with .less the you can “mix” one style rule “into” another.

.rounded_corners {
  -moz-border-radius: 8px;
  -webkit-border-radius: 8px;
  border-radius: 8px;
#header {

How’s It Work?

You enter your styles into a file with a .less extension and include them in a view or web form just like any style sheet.

<link href="/Content/Site.less" rel="stylesheet" type="text/css" />

An HTTP handler is configured to respond to requests for the .less files.

  <add validate="false" path="*.less" verb="*"
    type="dotless.Core.LessCssHttpHandler, dotless.Core" />

When a request arrives for a .less file it is the handler’s job to parse the .less file and transform it into standard CSS rule sets. .less does this using PEG Lib and offers the ability to both minify and cache the resulting CSS.

The source code is available on GitHub, so check it out for yourself. .less will let you write lean, mean style sheets.