Nesting multiple same type class inside one parent

98 Views Asked by At

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?

1

There are 1 best solutions below

6
Harry On

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;
    }
}