seenimurugan
seenimurugan

Reputation: 464

How to apply condition on grandparent from within the child class in Less

<div class="grandParent active"> /*active class added dynamically*/
   <div class="parent1">
    <div class="childOfParent1">  Some Text  </div>
   </div>
   <div class="parent2">
     <div class="childOfParent2">  Some Text  </div>
   </div>
</div>

Using Less how can i apply the child text color depending on grandParent class

.grandParent {
  .parent1 {
    .childOfParent1 {
      color : red;
      .grandParent:not(active) .parent1 .childOfParent1 {
        color : green;
      }
    }
  }
} 

The above is possible using the below code but i do not want to repeat the code

.grandParent {
  .parent1 {
    .childOfParent1 {
      color : red;
    }
  }
  &:not(active) .parent1 .childOfParent1 {
      color : green;
  }
}

Upvotes: 0

Views: 1718

Answers (1)

seven-phases-max
seven-phases-max

Reputation: 11820

The most maintainable code would be something like this I guess:

.parent {
    .child {
        color: green;
        .grandParent.active & {color: red}
    }
}

Or less DRY (if you really want to get use of :not):

.parent {
    .child {
        .grandParent              & {color: red}
        .grandParent:not(.active) & {color: green}
    }
}

See Changing selector order for more details on such & usage.


Following the comments below here's another variant:

.grandParent {
    .parent {
        .child {
            color: green;
            .active& {color: red}
        }
    }
}

[Well, slightly offtopic] Though if really takes into getting it maintainable, there're a few remarks:

  1. Avoid too specific selectors (so for this example I think either .grandParent or .parent are redundant actually).
  2. Never nest for the sake of nesting. Sometimes nesting is good but sometimes it's extremely ugly (see this nice brief answer for just a few of many reasons for never doing it blindly).
  3. DRY != maintainable. Often repeating one or two classes for "flat" styles are much better than writing a bloated and cluttered class hierarchy (Usually for such cases mixins and/or selector interpolation works better than plain nesting). E.g. instead of making it more easy modifiable (usually this is the only reason for being too heavy on DRY) think if you could write it the way you'll never want it to be modified at all.

Upvotes: 2

Related Questions