Curtis
Curtis

Reputation: 103428

How to write LESS with a parent selector (not top-level)

If I want to write the following CSS in LESS:

.foo{
   color:red;
}
.bar .foo{
   color:blue;
}

I can write:

.foo{
  color:red;

  .bar&{
      color:blue;
   }
}

However if I had the following LESS:

.top-level
   .foo{
     color:red;

     .bar&{
         color:blue;
      }
   }
}

This would produce a class of:

.bar .top-level .foo

How can I have .bar appear only one level above .foo?

Such as:

.top-level .bar .foo

The only way I can see to do this is the following code snippet, but it's not as neat as I'd like:

.top-level
   .foo{
     color:red;
   }
   .bar .foo{
      color:blue;
   }
}

Upvotes: 3

Views: 461

Answers (1)

Nicolas Carteron
Nicolas Carteron

Reputation: 339

I don't see how to avoid multiple selectors here, however I believe that rearranging your selectors might make the code "clearer" :

.foo {
  .top-level & {
    color: red;
  }

  .top-level .bar & {
    color:blue;
  }
}

This way you clearly identify that your styling two instances of the class .foo based on their parents. Not as neat as what you wanted, but pretty cool still.

Upvotes: 1

Related Questions