Evanss
Evanss

Reputation: 23142

Chain parent selectors with LESS from within selection?

I have multiple body classes and im hiding an element within these pages. When a class is added to the page with javascript then I want to show this element (assuming the body has these body classes).

This is working fine but can I rewrite it to avoid repetition?

.body-class-a,
.body-class-b,
.body-class-c {
  .element {
    display: none;
  }
}

.body-class-a.js-class,
.body-class-b.js-class,
.body-class-c.js-class {
  .element {
    display: block;
  }
}

Normally I would do something like this. However its not working as .infscrl-all-shown isn't above .body-class-a, its on the same level.

.body-class-a,
.body-class-b,
.body-class-c {
  .element {
    display: none;
    .infscrl-all-shown & {
      display: block;
    }
  }
}

Upvotes: 1

Views: 87

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241178

It looks like you would just need to remove the space between .infscrl-all-shown &.

In doing so, you are no longer selecting a descendant (since the space is removed between the class selector and the parent selector, &). The selector .infscrl-all-shown& will select the .body-* classes than also have the class .infscrl-all-shown.

.body-class-a,
.body-class-b,
.body-class-c {
  .element {
    display: none;
    .infscrl-all-shown& {
      display: block;
    }
  }
}

It will output the following:

.body-class-a .element,
.body-class-b .element,
.body-class-c .element {
  display: none;
}
.infscrl-all-shown.body-class-a .element,
.infscrl-all-shown.body-class-b .element,
.infscrl-all-shown.body-class-c .element {
  display: block;
}

Upvotes: 1

Related Questions