I want to create classes like below:
.colored{
&{
.red{background-color:red;}
.blue{background-color:blue;}
.gray{background-color:gray;}
}
}
and it is not working but if I write like this:
.colored{
&.red{
background-color:red;
}
&.blue{
background-color:blue;
}
&.gray{
background-color:gray;
}
}
then it works. Are there any reasons why the first version does not work as expected?
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
is equivalent to the following (because
&will be replaced by the parent selector which is.colored)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.