Book Image

LESS WEB DEVELOPMENT COOKBOOK

Book Image

LESS WEB DEVELOPMENT COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Less Web Development Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using namespaces to make your code reusable and portable


In programming languages, namespace is used to create a different scope for an object of a different origin. It prevents problems with such objects that have the same name. In Less, you can also create and use namespaces. They will help you to make your Less code more portable and reusable.

Getting ready

Open your text editor and create a file named project.less. If you don't use the command-line compiler, you will also have to create a valid HTML5 document, including the following lines of code in the head section:

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

How to do it…

  1. Create two mixins with the same name in the project.less file. You can, for instance, use the following code to create two mixins called mixin:

    .mixin(){
      color: red;
    }
    .mixin(){
      color: blue;
    }
    e1 {
      mixin
    }
  2. Now, compile the Less code you wrote in the project.less file and you will find that it will compile into the following code:

    e1 {
    color:red;
    color:blue;
    }
  3. After compiling your code, you can use the following Less code to wrap the first mixin in a namespace called #namespace, as follows:

    #namespace { 
      .mixin(){ 
        color: red; 
      } 
    } 
    .mixin(){ 
      color: blue; 
    } 
  4. Now the namespace mixin, can be utilized with the following Less code:

    e1 {
      #namespace > mixin;
    }
  5. Finally, the Less code from the preceding step will compile into the following CSS code:

    e1 { 
      color: red; 
    }

How it works…

The Less compiler doesn't throw an error for mixins with the same (or conflicting) names. The compiler compiles every matching mixin into the CSS code. You can read more about matching mixins in the Building loops leveraging mixins guards recipe in Chapter 6, Advanced Less coding.

Namespaces prevent conflicting names. In Less, a namespace starts with # and the code for it should be wrapped between accolades. A typical namespace will look as follows:

#namespace { .mixin(){} }

Mixins inside a namespace can be called by adding the namespace before the mixin call, which you can see in the following code:

#namespace > mixin;

You can also use the following code; it will generate the same result as you have obtained in the preceding code:

#namespace mixin;

Note

Note that the > sign in the preceding code is optional. The > sign has the same meaning as in CSS. In CSS, the > sign means a child (must be an immediate child, not any descendant).