Modular front-end development with LESS

I am constantly looking for ways to make my work as a front-end developer easier and more efficient, but it is only recently that I have paid my good friend CSS any real attention. This article will explore the benefit of organizing your code efficiently while keeping it reusable and modular.

Modular front-end development with LESS

I am constantly looking for ways to make my work as a front-end developer easier and more efficient, but it is only recently that I have paid my good friend CSS any real attention. The whole movement to make this sector of front-end development easier started with grid systems and the idea of object-oriented CSS, and has since been made easier with extensions to the language itself in the form of CSS pre-processors — the two most well-known being LESS and Sass.

This article will explore the benefit of organizing your code efficiently while keeping it reusable and modular. Let’s get started!

The tools of speedy CSS development

Object-oriented CSS is one of the best ways to make sure you are writing code that you can use almost anywhere, keeping the development time on future projects low. The basic principles of OOCSS are that your code should:

  • Separate structure and skin. Have separate classes for defining the way an element fits into the layout, and the way it is stylized.
  • Avoid location-dependent styling. The OOCSS GitHub project explains this best, by saying that instead of writing .container h2 you should use h2.tagline or whatever works semantically. This ensures that all h2 elements look the same.

When writing object-oriented CSS, keep in mind what you’re going to be using as your HTML markup. While you could write something like this:

<div class="blog-post">
	<h1>Article title</h1>
	<div class="meta">
		<p>Date published: <span class="date">12 January 2012</span></p>
	</div>
	<div class="post-body">
		<p>...</p>
	</div>
</div>

It would be better to write:

<article class="blog-post col_8">
	<h1 class="headline">Article title</h1>
	<p class="meta-information blog-post-meta">Date published: <time class="blog-date" datetime="2012-01-12">12 January 2012</time></p>
	<section class="post-body text">
		<p>...</p>
	</section>
</article>

And use CSS like this:

h1 { ... }
	.headline { ... }
.meta-information { ... }
	.blog-post-meta { ... }
time { ... }
	.blog-date { ... }
.text { ... }
	.post-body { ... }

Instead of prefixing each of these CSS rules with .blog-post, and thus making it too specific to reuse. But there are still some problems with this: you’re writing a bit too much HTML, and everything seems much too specific for a simple blog post. This is where LESS comes in, greatly simplifying the process.

LESS is a CSS pre-processor that extends the CSS language with unbelievably useful features. Ever since adopting it, styling web pages has been a breeze, and fun at that! While LESS boasts many useful features, the main three I’ll be concentrating on today are:

  • Variables. Define any variable like so: @color1: #df0290;and use it later in your code:
    .container { background: @color1 url('img/bg_gradient.png'); }
  • Mixins.Define useful functions with or without parameters:
    .box (@w: 500px, @h: 200px) {
    	display: block;
    	width: @w;
    	height: @h;
    }

    And use them later in your code:

    .modal-dialog ( .box(400px, 700px); }
  • Nested rules.Pretty self-explanatory, as I’m sure this is something you’ve been wishing for in CSS since you started using it:
    article {
    	font-family: serif;
    	line-height: 1.4;
    	h1 {
    		font: 2em bold sans-serif;
    	}
    	h2 {
    		font-size: 1.5em;
    		&.category { color: #666; }
    	}
    }

    An ampersand (&) refers to the parent rule. So &.category would translate to article h2.category once the LESS code had been compiled.

Using LESS, our blog post case study above can be simplified in the HTML to just this:

<article class="blog-post">
	<h1>Article title</h1>
	<p class="meta">Date published: <time datetime="2012-01-12">12 January 2012</time></p>
	<section class="post-body">
		<p>...</p>
	</section>
</article>

And the CSS would be:

/* Reusable global styles */
h1 { ... }
.headline { ... }
p { ... }
.meta-information { ... }
.col (@width) { width: 10% * @width; }
.date-published { ... }
.text { ... }

article {
	.col(8);
	h1 { .headline; }
	p.meta {
	.meta-information;
		time { .date-published; }
	}
	.post-body { .text; }

	&.blog-post {
		// perhaps some blog specific rules here?
	}
}

The need for organization in CSS

While the above is a very simple example, the case for organization in CSS becomes much more persuasive once you realize how large some web development projects are, and how multitudinous their need for styling is. A dialog in one place may look slightly different than in another, but that’s no reason to rewrite the whole rule! We can simply use a combination of LESS and OOCSS to achieve styling code that is modular, but specific, as demonstrated above.

One of the main benefits of putting this much thought into how you organize your style code is that you can separate the various functions of design. With this idea in mind, you might create a CSS (or, in this case, LESS) library that looked something like this:

/project/css/
reset.cssresets default browser styling
grid.lesssupplies mixins for a grid system, such as the .col(@width) mixin above
type.lesssupplies mixins for font styling as well as @font-face rules
colorscheme.lessLESS variables for the design’s various colors
interface.lessmixins for interface features like buttons, forms, and dialogs
layout.lessdesign-specific layout of the site
style.lessthe main stylesheet, including all of the above and adding in whatever site-specific styles are otherwise necessary

This level of organization is certainly overkill for very small pages, or one-page apps, but not for very large projects with many different pages. For even larger projects, you may have page- or function-specific styling files such as search.less or profile_page.less.

Be careful, though, about loading too many LESS files on a production server. Follow these guidelines for condensing your LESS code:

  • Make sure you always write nicely styled CSS. Go all out for development, and don’t take shortcuts in your code style. You’ll thank me later.
  • Use // comments instead of /* */ comments in LESS. These are removed by a LESS compiler.
  • Always use parametric mixins. Even when your LESS mixins don’t have variables, include an empty set of parentheses, like so: .border () { border: 1px solid black; } This will ensure that all LESS mixins aren’t included in the compiled code.
  • Compile LESS code, and then minify it with a CSS minifier. LESS has its own compiler, written for node.js. There is also a PHP compiler (and an online demo of that compiler). I have heard reports of the PHP LESS compiler having some definitive errors, but I haven’t noticed any myself.

Building style libraries to speed up front-end development

One of the main advantages you can have in development time is drawing from code that’s already been written. If you are working on a web application, don’t hesitate to start with Bootstrap — it supplies a lot of what you already need, and is probably the best and most comprehensive CSS framework out there, and it’s written in LESS!

Other LESS frameworks you might want to pay attention to are Preboot and Elements, both of which provide very useful mixins for you.

But depending on the type of work you do, the best way to build your library is to write the code yourself. To make this as efficient as possible, try and make every line of LESS code you write applicable in multiple contexts, and then save it for later. Obviously, you won’t be able to make every line of code context-independent, but much of the code you write can and should be used on multiple projects, so long as it is encapsulated in a LESS mixin and stored in a central location.

Another strategy is to use LESS templates, because styling a website goes much more quickly if you are used to the framework within which you’re working. An example of a colorscheme.less might be:

@background: 		#ffffff;
@textcolor: 		#252525;
@textcolor-strong:	#090909;
@textcolor-em:		#666666;
@textcolor-blockquote:	#aaaaaa;

@accent1:		#2d9681;
@accent2:		#f8a34b;

@warning:		#d4230f;

And so forth. By using a template like this for every project, you internalize the variable names and are able to quickly create style documents without thinking about the colors, but instead the function of each element. The same can be said of typography. If you have defined @font-headline in your type.less file, you can use it in an H1 or H2 element without having to consider exactly what font is necessary.

And it goes without saying that updating colors, fonts, and other crucial elements of the site’s design becomes so much easier and practically guarantees consistency.

A game plan

It may be hard to remember all of the particulars of what I’ve written above, but most of it can be extrapolated given just two general principles:

Abstraction and consistency. Keep your code modular so you can use it everywhere. Use patterns so you can remember them. Separate function from style, and details from big ideas. Don’t use location-dependent code unless you really have to.

Organize everything. Don’t just write reusable code — save it! In the directory where I keep my web projects, I have a lib directory that contains all reusable code, including libraries others have written, like Twitter Bootstrap and LESS Elements.

By following the techniques I’ve outlined, you’ll be able to build up a standardized library of LESS code that cuts down development time drastically. After abstracting away all the general functionality and styling of a website, you’re able to focus on what matters far more to the end user — how everything looks.

Image Credits:
Abstract Vector Image By Vectorportal.com
Less Logo by Less

Tagged with:

Delwin Campbell

Delwin Campbell is a web developer at No Enemies, based in Austin, Texas. He is a crazy person with too many hobbies; right now he’s growing a bonsai tree! Check out his personal site or add him on Google+.

Stay up to date with the latest web design and development news and relevant updates from Codrops.

Feedback 27

Comments are closed.
  1. This is a brilliant article. I’ve been looking into LESS lately and this article is a great introduction to it. Thank you!

  2. Hey, what do you use to compile you LESS files ?

    Right now, I use Less.app so in my HTML files I can link directly to my css file and have absolutely additional step when sending to production, which isn’t the case with Javascript.

    The issue I’m running into with LESS.app is that it doesn’t seem to handle variables and mixins shared across various less files as the javascript compiler seems to do. So organization is either impossible (need everything in one huge file), or ineffective because you need to copy the variables and mixins in each file.

    How do you deal with that ?

    • Well I found a solution :

      http://wearekiss.com/simpless

      Not as pretty as Less.app but at least it supports nested variables and hopefully mixins so that wouldn’t require any change in the workflow compared to Css and enable use of shared variables and mixins.

    • Yep, SimpLESS it’s a nice, cross-platform app to compile LESS- the only problem is that it uses still the 1.1 branch of LESS. For Windows WinLess is very nice http://winless.org/

  3. Very nice article Delwin, i myself have been using LESS for just mess around projects but I’m not looking into making it part of my daily CSS development as i currently have a couple of difference LESS compilers including LiveReload which helps speeding up working flow that much faster.

    Thanks for all the explanations and such as as until now i haven’t really had a game plan for how to layout my .less files but now i have a clear understanding of how and what i can be doing to continue improving my workflow on a daily basis.

    • Anything you use to write CSS. Set syntax highlighting mode to CSS, and it will catch 95% of LESS syntax. Or, for TextMate and vim (which I use), I think you can find LESS highlighting rule files.

  4. @ HammHetfield I think something might be set up wrong because Less.app should be able to handle files that are imported into other LESS files. Another alternative you can try is LiveReload which also has the ability to compile LESS and SASS files.

    @ Izulcybercafe: TextMate or Sublime Text work fine with LESS.

    With regards loading multiple different LESS files, I’ve been using this approach recently which is good from an organisational point of view but still enables you to output a single CSS file: https://gist.github.com/1407227

    • Any IDE or text editor will do, newer editors such as TextMate and Sublime Text come with support for LESS highlighting but you really don’t need anything specific as the CSS highlighter does a pretty good job anyway.

  5. Great article, really getting the hang of LESS lately and it improves my workflow a lot!
    I use Macrabbit’s Espresso and Codekit. Codekit is an app which not only can deal with LESS but als SASS, Stylus, HAML. LESS is dealt with syntax wise as if CSS, you have to manually select the CSS syntax and a major annoyance in Espresso is that due to the double “//” the inline comments get a bright red background-color. Anyone know if this can be changed in the preferences?

  6. It looks great, but isn’t it more complicated and an other file to load at start ? Does the performance of the site is slowed when we got a very huge css file ?

  7. Are there any opinions on which is better – LESS or SASS. I am looking into using one of them and they seem very similar. Other that the fact that SASS-Ruby and LESS-Javascript.

  8. Great article! Tons and tons of great info here I love it. I played around with Sass before and had a troublesome experience so I’ve stayed away from LESS for that reason… but with these tips I think I’ll have to jump back in and give it a try. Thanks!!

  9. I just recently started using LESS, as it’s the core of Dojo’s widget-theming system. I absolutely love the sanity it brings to CSS management, and wish I’d been thinking about my stylesheets this way all along, so old projects would be easier to manage.

  10. wow, great. I was looking these days for such information. It’s very useful. Thanks a lot for indications.

  11. And what about the responsive support ? If I put media queries on my styles.less it doesn’t work.

  12. amazing and it will very useful fro me cause I start new project with less css .Now I know how to naming css file as well.

  13. Why is it necessary to convert the less file to .css file? What is the purpose of having the plain .css file if you are compiling .less file?

  14. I’d love to start using LESS and I already read much about it, but for me the debugging is still a big problem. Compilers are great and all, but what about the way back – from compiled CSS to LESS? It’s not possible anymore to use Firebug to inspect elements and find the corresponding line in your LESS file since it’s totally different and there is almost no correlation. Is there a way to overcome this issue? What do you do about it?