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.