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.
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>
Create two mixins with the same name in the
project.less
file. You can, for instance, use the following code to create two mixins calledmixin
:.mixin(){ color: red; } .mixin(){ color: blue; } e1 { mixin }
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; }
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; }
Now the namespace
mixin
, can be utilized with the following Less code:e1 { #namespace > mixin; }
Finally, the Less code from the preceding step will compile into the following CSS code:
e1 { color: red; }
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;