LESS CSS tutorial – the beginners guide to a CSS preprocessor. Learn about LESS and save your time repeating CSS code.

LESS CSS tutorial – the beginners guide to a CSS preprocessor.

What is less ?

LESS is a CSS preprocessor. It can solve common code problems, such as code repetition. LESS is crossbrowser friendly. Very intuitive and agile tool.
This is a short tutorial of LESS CSS including some tips.
Before we start i want you to know that there are other CSS preprocessor like SASS, that will be covered in another post.

This tutorial will cover the following:

  • What is the DRY(Don’t repeat yourself) design pattern. How can be implement on CSS using LESS CSS
  • Short introduction to LESS
  • Editors and IDE
  • Getting started with LESS
  • LESS CSS nesting – LESS gives you the ability to use nesting in your CSS!
  • LESS parameters – Finally variables in your CSS
  • LESS functions and operations
  • LESS mixins
  • Final Tips

DRY ( don’t repeat yourself )

DRY is not just a design patter, but it is a way of thinking and a principle of software development. Simple steps to follow, so you can get the idea of DRY.

  1. Identify repetitive and reusable code.
  2. Instead if copy/paste huge blocks of CSS code, you can create a function (Mixin) with LESS to be called when you need those styles
  3. Make use of the Nested Rules – which will cut down some of your repetitive code.
  4. Use variables, color functions, operators and mixins to separate structural code from representational code

By implementing DRY principles in your code you add also the KISS (Keep it simple, stupid!) design principle. When you need to change all the colors or fonts in your website – do it from one place via variables. When you need to change the behavior of all modal windows or popups – do it from one place using a mixin that generates those styles.
Q: Why you should bother with all of this?
A: The code repetion problem will expand in big and growing applications. At some point your code will become unmaintainable.

Short introduction to LESS

LESS expands the capabilities of CSS. It adds more features and agile solutions to common CSS problems. LESS is crossbrowser friendly.

Editors and IDE

A preferred LESS editor – sublime text 2.

LESS syntax is supported by many IDE’s like – VIM, Aptana Studio, Coda 2

Getting started with LESS

First you must download the latest less.js from github – https://github.com/cloudhead/less.js or the official site http://lesscss.org

You will need to create a file with .less extension to put your styles there. Preferred is styles.less

Add the less.js and styles.less to your HTML’s head section:

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

Note the rel attribute of the link element must end with /less in order for LESS to work. You are also required to include the less.js script immediately after the link to the style sheet. If you’re using HTML5 syntax, you can omit the type=”text/css” and the type=”text/javascript”, but do not omit rel=”stylesheet/less”.

Server-side version of LESS – The easiest way to install LESS on the server is with Node Package Manager (NPM). Installations are available for Windows, OSX, UNIX

LESS CSS nesting

// Brand, links, text, and buttons
.navbar {
    text-align: center;
    // Hover and active states
    .brand:hover {
        text-decoration: none;
    }
    .btn-danger{
        float: right;
    }
    // Website or project name
    .brand {
        float: left;
        display: block;
        padding: 8px 20px 8px;
        color: @white;
    }
    // Plain text in topbar
    .navbar-text {
        margin-bottom: 0;
        line-height: 40px;
        color: @navbarText;

        a:hover {
          color: @white;
          background-color: transparent;
        }
    }
    // Buttons in navbar
    .btn,
    .btn-group {
        margin-top: 5px;
    }
    .btn-group .btn {
        margin-top: 0;
    }
}

LESS gives you the ability to use nesting in your CSS!
With the use of & combinator you can nest selector to concatenate the child to its parent selector, instead of acting as a descendant. This is very usefull for pseudo-classes like :hover, :visited and :focus.
With the ability to nest styles your code is more readable and consistent.

LESS parameters

// Accent colors
// -------------------------
@blue:                  #049cdb;
@blueDark:              #0064cd;
@green:                 #46a546;
@red:                   #9d261d;
@yellow:                #ffc40d;
@orange:                #f89406;
@pink:                  #c3325f;
@purple:                #7a43b6;

// Typography
// -------------------------
@sansFontFamily:        "Helvetica Neue", Helvetica, Arial, sans-serif;
@serifFontFamily:       Georgia, "Times New Roman", Times, serif;
@monoFontFamily:        Monaco, Menlo, Consolas, "Courier New", monospace;
@smallFonts:               Helvetica, Arial, sans-serif;

Finally variables!

Variables in LESS are defined via the keyword ‘@’
Variables can have value type of string or number. You can easy separate the presentational part of your layout like colors and fonts. Using variables will help you keep the consistency of your code. When you have all colors defined you don’t need any more to search and scroll for their hex values.

It’s a good practice to define all your variables in separated LESS file and include it on top of your main LESS file

LESS functions and operations

@linkColor:             @blueType;
@linkColorHover:        darken(@blueType, 15%);
@gridColumns1200:            12;      
@gridColumnWidth1200:     90px;
@gridGutterWidth1200:     10px;
@gridRowWidth1200:        (@gridColumns1200 * @gridColumnWidth1200) + (@gridGutterWidth1200 * (@gridColumns1200 + 1));

When using functions and arithmetical operations, the result will be a value
You can add, multiply or divide – pixel, em, %, hex values. Functions are mainly used to help you stick to a color scheme in your coding process. There is no need to go into photoshop and lighten a color with 10% for example.

LESS mixins

// Gradients
#gradient {
  .horizontal(@startColor: #555, @endColor: #333) {
    background-color: @endColor;
    background-image: -moz-linear-gradient(left, @startColor, @endColor); // FF 3.6+
    background-image: -webkit-gradient(linear, 0 0, 100% 0, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+
    background-image: -webkit-linear-gradient(left, @startColor, @endColor); // Safari 5.1+, Chrome 10+
    background-image: -o-linear-gradient(left, @startColor, @endColor); // Opera 11.10
    background-image: linear-gradient(to right, @startColor, @endColor); // Standard, IE10
    background-repeat: repeat-x;
    filter: e(%("progid:DXImageTransform.Microsoft.gradient(startColorstr='%d', endColorstr='%d', GradientType=1)",argb(@startColor),argb(@endColor))); // IE9 and down
  }
}

Mixins are functions that let you implement OOCSS (Object Orientated CSS) principles in your styles. By separating identical styles from elements and using css class inheritance, you can decrease the number of repeated styles. That will help you reduce the CSS file size. This practice is the key foundation of DRY principles and design pattern. You can read more about OOCSS in the following links: http://www.slideshare.net/stubbornella/object-oriented-css, http://www.slideshare.net/stubbornella/what-is-object-oriented-css.

The execution of a mixin will return a block of CSS code. For example all your modal windows will include the .modal-behaviour() and .border-radius() mixins

If you were wondering, can be passed an argument to a mixin? Yes you can. That is another power full feature ot he mixins. You can set default values to your arguments, and pass other to override them. With passing a parameter to a mixin it becomes more flexible and reusable.

// Box sizing Mixin
.box-sizing(@boxmodel) {
  -webkit-box-sizing: @boxmodel;
     -moz-box-sizing: @boxmodel;
          box-sizing: @boxmodel;
}
// Block level inputs
.input-block-level {
  display: block;
  width: 100%;
  min-height: 30px; 
  .box-sizing(border-box); // using a mixin
}

Another good feature of Mixins is to store them in namespaces. For example you want all your font mixins to be stored in #fonts namespace:

// FONTS
// --------------------------------------------------

#font {
  #family {
    .serif() {
      font-family: @serifFontFamily;
    }
    .sans-serif() {
      font-family: @sansFontFamily;
    }
    .monospace() {
      font-family: @monoFontFamily;
    }
  }
  .shorthand(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) {
    font-size: @size;
    font-weight: @weight;
    line-height: @lineHeight;
  }
  .serif(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) {
    #font > #family > .serif;
    #font > .shorthand(@size, @weight, @lineHeight);
  }
  .sans-serif(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) {
    #font > #family > .sans-serif;
    #font > .shorthand(@size, @weight, @lineHeight);
  }
  .monospace(@size: @baseFontSize, @weight: normal, @lineHeight: @baseLineHeight) {
    #font > #family > .monospace;
    #font > .shorthand(@size, @weight, @lineHeight);
  }
} 

Final Tips

  • Keep your code simple and consistent
  • Use DRY principles where possible
  • For better understanding and implementation of OOCSS use a LESS framework like Bootstrap
  • There are many many more things that can be said about LESS. For example LESS preferred frameworks. Advanced techniques for rapid web development and prototyping. Fluid and fixed layouts. Grid system generator mixins. Best practices for development and production environments. Mobile and tablet development. Quick retina displays enhancements and support. All topics will be featured in a separated advanced LESS CSS tutorial. If you enjoy writing less code, please check out the next tutorial as soon it is available :)

    There are useful links available at the end of the presentation.

    In general – write LESS do more! This is the major feature of LESS.
    The LESS CSS tutorial is formatted as a presentation – LESS presentation

Leave a Reply

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