Advanced CSS with LESS

By  ·  · CSS Tips and Tricks, Featured0 Comments ]

CSS Tips and Tricks IconIf you’re anything like us, your familiarity with programming languages like PHP, JavaScript, and ColdFusion – or even basic HTML – has left you longing for a way to condense your CSS, make it more intelligible in its organization, and have the option for the code to be less linear and more visually interpretable. Key features of the aforementioned programming languages, such as the ability to use variables, nest tags and markup, and create data or variable arrays, all permit coders to more efficiently write scripts that are easily read later on and by other coders. CSS, however, innately lacks all of these features – but that doesn’t mean stylesheet authors need continue to suffer crossed-eyes and headaches while writing hundreds and hundreds of lines of code and then trying to read and edit it another day!

How is that possible? With LESS! Hold your horses, though – before we delve into an introduction to LESS and its usage, it’s worth covering the foundations of CSS (Cascading Stylesheets) and how they are carried over into LESS.

CSS Basics

It’s important to understand how CSS is implemented prior to working with LESS markup, because while LESS offers the ability to code in familiar formats with variables and the like, it does not manipulate the core functioning of CSS styling. The overarching rules governing how browsers apply stylesheets to Web page content apply to CSS written in LESS format, as well. Here’s what you need to know:

  • CSS is linear: by nature, stylesheets are coded unilaterally (start-to-finish, top-to-bottom) because browsers interpret and apply them linearly – hence, the “cascading” in the name. What this means is code that comes first in the stylesheet document is applied to the Web page first, followed by all of the subsequent code in order. If elements, IDs, or classes are repeated, whatever declarations are made later in the document overwrite the earlier declarations. LESS operates the same. For example, this code
    body { background-color: #fff; }
    div { ... }
    table { ... }
    ...
    body {background-color: #fee; }

    would result in the body of the page having a tinted background rather than a white background as declared at the start of the stylesheet. The same principle applies to repeated declarations within elements, like so:

    body {
    	background-color: #fff;
    	color: #000;
    	font-family: Helvetica, sans-serif;
    	...
    	background-color: #fee;
    }

    This code would again overwrite the original white background color to tinted.

  • Style rules are applied hierarchically: this means that declarations for the <body> tag are applied to all tags enclosed within it, and so on. It also means there is an established order in which style rules are applied – beginning with the style of enclosing tags, down to declarations for the specific tag, next to classes applied to an element, and finally to the style="" attribute specified in the tag, if there is any. LESS also applies style declarations according to the CSS hierarchy of rules. For example, the following CSS
    body { color: #000; }
    div { color: #fff; }
    .red { color: #f00; }

    would result in body text that is black, text enclosed within <div> tags that is white, and text contained within a tag with the .red class that is colored red. It would look something like this (code is faded to demonstrate underlying markup creating the style changes within the content):

    <body>
    Sample
    <div>
    DIV content
    </div>
    <div class="red">

    DIV with class
    </div>
    </body>
  • The hierarchy rule can be implemented in property declarations: you are able to anticipate structure of a Web page and create a CSS declaration that will apply to elements contained within a certain hierarchy of elements. This seems a bit complicated, but an example should clarify:
    div ul li em { color: #f00; }

    That style will only apply to <em> tags that are nested within an item in an unordered list that is contained within a <div>. Markup utilizing this form of hierarchical CSS could look something like this:

    <div>
    <ul>
       <li>
    • Test content</li>
       <li>
    • Now to show an <em>em tag style</em></li>
    </ul>
    </div>
    <ul>
       <li>
    • An uncolored <em>em that is not applicable</em> under the example CSS</li>
    </ul>

    As you can see, the CSS style only applies to the element that matches the exact hierarchy in the stylesheet declaration. And as with the other rules discussed, this same one applies to LESS formatting.

In other words, we can sum up the basic rules of CSS application thus: the more specific the CSS declaration, the higher priority it has. Style markup that affects the whole of the document has the least priority and will easily be superseded by markup that defines properties for individual elements which is further overruled by specific element attributes. This umbrella rule also forms the foundation of LESS formatting for stylesheets, so it’s important to understand before we continue.

What is LESS?

LESS, or Leaner CSS, is not technically a new programming language. When you code in LESS, you are writing a modified version of CSS – the same general syntax and language applies. LESS simply offers you the ability to more efficiently and dynamically write CSS stylesheets, after which you either use local software to convert the LESS code into a standard CSS document, or you run plugins or scripts on your Web site that translate the LESS into CSS on-the-fly, server-side.

With LESS, you can use nested code, variables, and other shorthand to better organize and more quickly write stylesheets that would otherwise be long, tedious, and rife with potential for duplicated code and endless repetition of declarations as you create complicated styles for your sites. LESS simplifies the process of coding for advanced designs and enables coders to more easily make changes in the future and find elements, properties, and declarations within complex stylesheets.

How Do I Use LESS?

Before we get into the actual usage of LESS syntax, we should discuss how to implement LESS code within your designs. As there is no such thing as native browser support for LESS, at some point along the way from coding to live viewing of your site within a browser, the LESS code must be translated into standard CSS for the browser to use.

There are several options for running LESS conversion on your server, from built-in Ruby gems to various software plugins for WordPress, PHP, and so on. If you would like to have the option of uploading LESS files directly to your Web site without compiling them into CSS first, simply search for options for your chosen CMS.

We prefer to code stylesheets in LESS and then compile them using local software before uploading the CSS documents to our servers. As we primarily use Macs for our development work, our preferred software is a lightweight app for MacOS, {less}.app. If you also work on a Mac, we highly recommend {less} for compiling your LESS code into CSS.

What Does LESS Code Look Like?

With all of that important background information out of the way, we can finally get down and dirty with some actual LESS coding! The key features of LESS are variables, mixins, nested rules, and operators:

Variables

Ever get sick and tired of trying to find and replace every instance of a color you specified dozens and dozens of times within a stylesheet when slightly changing the palette of a design? Or how about font sizes? Or border styles? Or pretty much any number of properties that are frequently repeated over and over within a stylesheet? No more! With LESS, you can declare a variable at the start of the document that you use throughout the stylesheet. If you suddenly decide that every instance of font-size: 1em is just a wee bit too small, you don’t have to search for those needles in the haystack with a magnifying glass, going cross-eyed in the process and all the while missing just one needle that completely throws off your design. The LESS usage looks like this:

@base_font: 1.2em;

p { font-size: @base_font; }
div.base-font { font-size: @base_font; }
input { font-size: @base_font; }

In the future, you can change all of the instances of the font sizes by changing the one @base_font variable, and that’s it!

Mixins

Say you want to include a few properties in a multitude of declarations. With standard CSS, you have to repeat them over and over again within each set of declarations. The mixins in less allow you to treat a class as an array of properties that you can call within other declarations, so rather than repeating the same lines of code til you develop carpal tunnel, you can create a class that you refer to within each element. A side benefit? Just like variables, if you want to make a change that applies to all of the instances sometime in the future, you only have to change one class! For example:

.forms {
	background: #fff;
	font-family: Arial, Helvetica, sans-serif;
	font-size: 1em;
	color: #000;
	border: 1px solid #999;
}

input[text], input[search], textarea { .forms; }
input[submit], button { .forms; font-weight: bold; }

This feature has saved our poor fingers from the seemingly incessant repetition of using rounded corners and other CSS3 properties that necessitate the usage of browser prefixes (i.e. -o-, -moz-, and -webkit-). With LESS, we can create a rounded corner class and call that however often we like with just a few characters!

Nested Rules

Rather than creating infinite chains of elements to define properties for specific arrangements of nested HTML, you can use LESS to actually nest the CSS the way you anticipate nesting your HTML. The best way to picture how LESS saves you precious time and effort in this manner is a comparison between example CSS and its equivalent LESS code:

CSS

ol { margin: 0; }
ol li { font-size: 1.2em; }
ol li h2 { color: #f00; }
ol li p { font-weight: bold; }

LESS

ol {
	margin: 0;
	li {
		font-size: 1.2em;
		h2 { color: #f00; }
		p { font-weight: bold; }
	}
}

Not only is it faster to write when you don’t have to repeat the exponentially-growing chain of elements, but it’s much easier to visualize the relationship between the nested LESS than those complicated chains of CSS. The LESS takes on a correlated appearance to your HTML and PHP – translating between the two becomes far more intuitive.

Operators

We’ve been tremendously frustrated in the past when trying to calculate proportional dimensions for CSS layouts in our designs. The operators in LESS are a true life-saver! As opposed to manually calculating the end result of relationships between the widths of static columns, we can use the formula itself and let LESS do the calculations instead. This feature becomes especially useful in conjunction with variables, like so:

@base_width: 136px;

#container { width: @base_width * 3; }
#sidebar { width: @base_width; }
#main { width: @base_width * 2; }

Thanks to LESS, we get to disregard the added step of calculating the proportional widths, but if we decide to change the base width of the relationship, adjusting the variable is the only step! Gone are the days of repeatedly recalculating proportional properties to make subtle adjustments during the development process!

Conclusion

We hope this introductory guide to LESS has helped you to discover a better way to code all of your CSS. For even more information on LESS and its usage, check out the LESS documentation. And please feel free to share your LESS tips and advice below, and we’d love to hear innovative ways you’ve implemented LESS in your development process and useful LESS code you’ve discovered or written.

Tags: , , , , , , , , , , , , ,

No Comments

Please use the form below to leave a comment on this post.

Leave a Comment

You must be logged in to post a comment.