Reason:
It is because of the way nesting works (and is supposed to work) in Less. When you nest a selector under another selector, the inner selector is considered as applicable for an element which is a child of the element represented by the outer selector.
The below is code
.colored{
&{
.red{background-color:red;}
.blue{background-color:blue;}
.gray{background-color:gray;}
}
}
is equivalent to the following (because & will be replaced by the parent selector which is .colored)
.colored{
.red{background-color:red;}
.blue{background-color:blue;}
.gray{background-color:gray;}
}
Now as I mentioned earlier, this would compile to .colored .red, .colored .blue, .colored .gray (note the space between the selectors).
On the other hand when you insert the & immediately before .red, .blue, .gray, it means that the parent selector and the nested selector apply to the same element (and not a child). The selectors that it would output is .colored.red, .colored.blue, .colored.gray (note that there is no space).
Solution:
This is the same code as in your question and it is the recommended solution. I am posting it again in the answer only to make it complete.
.colored{
&.red{
background-color:red;
}
&.blue{
background-color:blue;
}
&.gray{
background-color:gray;
}
}