Stylin’ with CSS

The Blog and Books of Charles Wyke-Smith

Doing More with Less

by Charles Wyke-Smith

Writing CSS in Less enables you to write CSS that is more concise, faster to write and far easier to understand when you revisit it. The primary benefit is that Less lets you nest your CSS rules inside one another the same way as HTML tags are nested, so the relationship between the HTML markup and the CSS that styles it is much clearer, but there are many other advantages, and this article looks at some of the most useful features that Less offers.

CSS Preprocessors offer capabilities such as variables, mixins and, as mentioned, nesting, to speed your CSS writing and editing. I'll cover each of these capabilities in this article. The two most popular CSS preprocessors are Less and Sass. They are on the surface very similar, as you can see in this Less and Sass comparison.

The Less engine, which you only have to add to your pages and never touch, is written in Javascript, so this allows you the option to either run Less client-side, or install and run iton your Web server. I am going to show the more simple client-side method, where the Less-format style sheet is simply uploaded to the server like any other CSS file, and is processed by the less.js file into regular CSS as the page loads. Unless your Less file is tens of thousands of lines, the processing happens in a matter of milliseconds, so there is not much downside in compiling at runtime on the client.

Setting Up to Use Less

First, download a copy of Less, copy and paste the displayed code into a blank file, and save it as less.js. Typically, this goes in your js folder along with your other JavaScript files.

Next, create a new file called styles.less and put in your css folder.

Finally link both files to your HTML document, like this

     
  <link href="css/styles.less" rel="stylesheet/less" type="text/stylesheet" />
  <script src="js/less.js" type="text/javascript"></script>
   

Two important points to note here—first, the stylesheets must be listed before the less.js file so that they load first. Second, the rel attribute for Less stylesheets uses stylesheet/less, and not the usual stylesheet/css.

Less Concepts

Let's first look at two of the most useful Less features: variables and nesting.

Variables

The biggest problem with CSS is that you cannot follow a fundemental good-practice coding principle known as DRY—Don’t Repeat Yourself. For example, you probably re-stating color and border-width values every time a color or border is defined, as they tend to be consistant across your design. With Less, you can define a variable name such as green-blue for a color and then assign a color value to that variable, such as #069. You can then just use the variable name wherever you would have used the color value.

For example, this code


div {
	border: 1px solid;
	border-color: #069;
    }
a {  
	color: #069;  
    }

...can be written in Less as...


@blue-green:#069; /* define variable */

div {
	border: 1px solid;
	border-color: @blue-green; /* use variable */
    
    a {  
        color: @blue-green;  /* use variable */
    }
}

You can use a variable to define as many instances of the color as you wish, and if you want to change that color later, you only have to do so in one place. Variables alone make it worth using Less. This example also illustrates Less nesting, which to me is its most powerful feature, so let's next look at the concept of nesting in more detail.

Nesting

Using Less' nesting capability further helps remove redundancy from your code, and makes it far easier to read. As a simple example, here's a div that contains some text.


<div id="info_box">
    <p>Less is a <strong>CSS pre-processor</strong>.</p>
</div>

Let's style this HTML into a onscreen box with regular CSS


div#info_box {
    width:300px;
    border:1px solid #999;
    border-radius:5px
}
div#info_box p {
    font-family:arial,sans-serif;
    font-size:20px;
}
div#info_box strong {
    color:#39C;
}

Less is a CSS pre-processor.

Here is the same styling re-written in Less


div#info_box {
    width:300px;
    border:1px solid #999;
    border-radius:5px;
    text-align:center;
	
    p {
        font-family:arial,sans-serif;
        font-size:20px;
		
        strong {
            color:#39C
        }
    }
}

Note how the child elements are inside of the curly barckets of their parents, just as nested markup elements are nested within their parent tags. Note how I carefully line up the closing curly bracket of each element exactly under the element name so that I can see that I am correctly closing each rule. I also add an empty line between each level of the nesting for clarity, but that is a personal preference and you don't have to do that. Part of the reason I do this is that coding tools such as Dreamweaver don't yet understand how to color code Less, so this helps me see where each rule begins.

As you can see, the scope, div#info_box, is only stated once. It's also much easier to see what is being inherited, such as the text-align on div#info_box, which also will be inherited by the child p tag.


<nav id="horizontal_menu">
	<uL>
    	<li><a href="#">Clothing</a></li>
        <li><a href="#">Electronics</a></li>
        <li><a href="#">Appliances</a></li>
        <li><a href="#">Furniture</a></li>
    </ul>
</nav>

In this conventional CSS markup, I have to restate the scope, horizontal_nav, on every rule, or my styles will “leak out” of this scope into other elements with the same tag names elsewhere on the page.

A Real-World Example

Here's a typical piece of code that I use in some variation in just about every site I develop—an unordered list styled as a horizontal navigation element. Here's the HTML.


<nav id="horizontal_menu">
    <ul>
    	<li><a href="#">Clothing</a></li>
        <li><a href="#">Electronics</a></li>
        <li><a href="#">Appliances</a></li>
        <li><a href="#">Furniture</a></li>
    </ul>
</nav>

The CSS might look like this


	#horizontal_menu {
		text-align:center;
	}
	#horizontal_menu ul {
		display:inline-block;
	}
	#horizontal_menu li {
		float:left;
		list-style-type:none;
	}
	#horizontal_menu li + li a {
		border-left:1px solid #2889b7; 
	}
	#horizontal_menu a {
		display:block;
		padding:3px 5px;
		background:#E5F3F7;
		color:#2889B7;
		text-decoration:none;
	}
	#horizontal_menu a:hover {
		background:#E5F3F7;
		color:#2889B7;
	}

This HTML and CSS results in this horizontal menu.

Again, as in any conventional CSS markup, I have to restate the scope, horizontal_nav, for every rule.

Here is the same code, written in Less format.

@dark_blue:#2889B7
@light_blue:#E5F3F7;

#horizontal_menu2 {
    font-family:arial, sans-serif;
    text-align:center;
		
    ul {
        display:inline-block;
        	
        li {
            float:left;
            list-style-type:none;

            & + li a {
                border-left:1px solid @dark_blue;
            }

            a {
                display:block;
                padding:3px 5px;
                background: @light_blue;
                color:@dark_blue;
                font-size:14px;
                text-decoration:none;

                &:hover {
                    background:@dark_blue;
                    color: @light_blue;
                }
            }
        }
    }
}

This example shows a more real-world use of variables and nesting. It also illustrates the Less & combinator which allows you to concatonate (join) a rule to its parent selector. This is used with pseudo-classes such as hover, and with conbinator selectors such as +, both of which are illustrated here.

Finally, I'l mention that Less is very fussy about syntax. If you leave off a ; at the end of a regular CSS declaration, the only penalty is that the rule is skipped from that point on, but with Less, the page does not load at all, or at best, no styles are applied to the page. However, it's easy to automatically validate your Less each time you save using Less.app. Just drag your Less file to the Less.app window one time to register it, and you will see a Success message (or a error indicating the problem line number) every time you save. Finally, note that due to browser security restrictions, you can't run Less locally in your PC's browser—you need to test your Less pages on a Web server so that the less.js file can execute.

Less is one of those innovations that once you use it, you never want to go back to regular CSS. It will really accelarate your styling efforts, and it is just so much easier to read and to understand exactly what is happening in your CSS. Happy coding!

Categories

Tags

Leave a comment

More posts