More semantic HTML with LESS CSS

In my ongoing quest to make the web a better place, or at least in the places I have a hand in, I was looking for a way to easily create CSS for POSH HTML. And I found a way in the shape of LESS. LESS calls itself “the dynamic stylesheet language”. And they don’t lie.

I had come across LESS before, but never really paid attention. I loved creating well structured CSS for my HTML, but never realised that my HTML was lacking.

My HTML was usually a trade-off between ease of development and semantics. I usually use a hand made CSS grid system. That makes it easy to divide the layout in columns by applying a .col2 class to a div that needs to be 2 columns wide. It would mean a lot of repeated lines of CSS if those rules would needed to be specified on every selector in the CSS. The result was that a lot of those non-semantic classes ended up in the HTML.

But now there don’t have to be anymore trade-offs because of LESS. And it has been a while since I was this excited about a web technology.

LESS allows you to create code very similar to CSS which compiles into valid CSS. It has many great features like variables, nested declarations, calculations and color functions, but there is one feature which is really going to change the way I work. And that feature is Mixins.

Say we have to following markup:


And the following CSS:

.col1, .col2{
      float: left;
      padding: 0 20px;
      width: 280px;
      width: 600px;

The goal is to have to make the article 2 colums wide and the aside 1 column. In the old days that, to me, would mean giving the article a class=”col2” and the aside a class=”col1”. But now behold the power of mixins! In the LESS CSS document declare just this:


A mixin basically means you can reuse previous declarations by simply calling them within another declaration. After compiling the LESS into CSS all the styles associated with .col2 would have been inserted into to article selector and the .col1 rules into the aside selector. Pretty awesome! Even better is that the HTML can be kept completely clean of non-semantic classes!

Think about how you could use this to keep .clearfix out of your HTML. Or to easily declare border-radius (with all the vendor prefixes) on elements by just inserting .rounded-corners;. You van even declare parameters for mixins. That means that you can use our new .rounded-corners class like this: .rounded-corners(10); to give the element a border-radius of 10px;.

You should definitely read up on LESS CSS on!

One Response to More semantic HTML with LESS CSS

  1. Pingback: More on LESS and semantics | Is it happening?

Leave a Reply

Your email address will not be published. Required fields are marked *